2017-07-03 56 views
0

我有一個由我定義的屬性數組,我得到了他們兩個都需要組合成輸出數組的散列值。請讓我知道最簡單的方法來做到這一點。將數組值與散列值結合起來

屬性 = [:USER_ID,:PROJECT_ID,:TASK_ID,:日期,:time_spent,:評論]

entry_hash = { 「用戶」=> 1, 「項目」=> [8 ],「任務」=> [87],「日期」=>「05/22/2017」,「時間(小時)」=>「1」,「評論」=>「是」}

它被組合我要像

輸出 = { 「USER_ID」=> 1 「PROJECT_ID」=> 8, 「TASK_ID」=> 87, 「日期」=> 6的散列/ 22/2017,「time_spent」=> 1,「comment」=>「是」}

感謝您的幫助!

回答

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"} 
+0

感謝這有助於!我現在有另一個問題。當我嘗試通過執行model.create!(輸出)將輸出哈希插入到數據庫中時,它無法這樣做。任何幫助,將不勝感激 – Archie123

+0

@ Archie123你得到什麼類型的錯誤?你可以展示它的屬性是什麼模型? –