将数组的值与散列

时间:2017-07-03 18:44:55

标签: ruby-on-rails-4

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

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

entry_hash = {“User”=> 1,“Project”=> [8],“任务”=> [87],“日期”=>“05 / 22/2017“,”时间(小时)“=>”1“,”评论“=>”是“}

当它合并时,我想要像

这样的哈希

输出 = {“user_id”=> 1,“project_id”=> 8,“task_id”=> 87,          “日期”=> 2017年6月22日, “time_spent”=大于1, “注释”=> “中是”}

感谢您的帮助!

1 个答案:

答案 0 :(得分: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"}