【问题标题】:Combining the values of an array with the values of hash将数组的值与哈希值组合
【发布时间】:2017-07-03 18:44:54
【问题描述】:

我有一个由我定义的属性数组,我得到了一个哈希值,我需要将它们组合成一个输出数组。请告诉我最简单的方法。

属性 = [:user_id, :project_id, :task_id, :date, :time_spent, :comment]

entry_hash = {"User"=>1, "Project"=>[8], "Task"=>[87], "Date"=>"05/22/2017" , "时间(小时)"=>"1", "评论"=>"是"}

当它被组合时,我想要一个类似的哈希

输出 = {"user_id"=>1, "project_id"=>8, "task_id"=>87, "date"=>6/22/2017,"time_spent"=>1,"comment"=>"yes"}

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails-4


    【解决方案1】:

    试试这个

    attributes = [:user_id, :project_id, :task_id, :date, :time_spent, :comment]
    # puts attributes.inspect
    entry_hash = {"User"=>1, "Project"=>[8], "Task"=>[87], "Date"=>"05/22/2017", "Time (Hours)"=>"1", "Comment"=>"yes"}
    # puts entry_hash.inspect
    
    output = {}
    a = 0
    entry_hash.each do |key,value|
        if value.class == Array
            output[attributes[a]] = value.first.to_s
            #output[attributes[a]] = value.first.to_i   //also you can convert them into int
        else
            output[attributes[a]] = value
        end
        a += 1
    
    end
    #puts output.inspect
    #{:user_id=>1, :project_id=>"8", :task_id=>"87", :date=>"05/22/2017", :time_spent=>"1", :comment=>"yes"}
    

    【讨论】:

    • 感谢帮助!我现在有另一个问题。当我尝试通过执行 model.create!(output) 将输出哈希插入数据库时​​,它无法这样做。任何帮助将不胜感激
    • @Archie123 你得到了什么类型的错误?以及它是什么模型,你能展示它的属性吗?
    猜你喜欢
    • 2012-10-11
    • 1970-01-01
    • 2021-05-08
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多