在rails hash上迭代

时间:2016-01-07 08:06:58

标签: ruby-on-rails hash iteration

我有这样的哈希,我在控制器中得到params的值

参数:

{
"utf8"=>"✓",   
"authenticity_token"=>"WwNhv6pbXMvQWamzcKTm6gixDEUvvbrsZ7OrMR8RSAA=",  
"form_holiday"=>{
  "user_id"=>"3", 
  "1"=>{"year_before"=>"2014", "day_before"=>"22", "year_now"=>"2015", "day_now"=>"20"}, 
  "2"=>{"year_before"=>"", "day_before"=>"", "year_now"=>"", "day_now"=>""}, 
  "3"=>{"year_before"=>"2014", "day_before"=>"10", "year_now"=>"2015", "day_now"=>"30"}}
}

如何迭代此哈希并获取" 1,2,3"的值? ?

我想改变它,看起来如下:

{"utf8"=>"✓", 
 "authenticity_token"=>"WwNhv6pbXMvQWamzcKTm6gixDEUvvbrsZ7OrMR8RSAA=", 
 "form_holiday"=>{
   "1"=>{"user_id"=>"1", "year_before"=>"2014", "day_before"=>"22", "year_now"=>"2015", "day_now"=>"20"}, 
   "2"=>{"user_id"=>"2", "year_before"=>"", "day_before"=>"", "year_now"=>"", "day_now"=>""}, 
   "3"=>{"user_id"=>"3", "year_before"=>"2014", "day_before"=>"10", "year_now"=>"2015", "day_now"=>"30"}}
}

这是我目前的代码:

 year_before = ""
  year_now = ""
  holiday = ""
  @users = User.find(:all)
 if params[:form_holiday]

 hash_params = params[:form_holiday]

 hash_params.each do |key, value|
  if value
    value.each do |key2, value2| 
      if key2 == "user_id"      
        holiday = Holiday.where("user_id = #{value2}") rescue nil
      end
      if key2 == "year_before"
        year_before += "#{value2},"
      end
      if key2 == "day_before"
        year_before += "#{value2}"
      end
      if key2 == "year_now"
        year_now += "#{value2},"
      end
      if key2 == "day_now"
        year_now += "#{value2}"
      end
     end
    holiday.year_before = year_before
    holiday.year_now = year_now
    holiday.save                
   end
  end
 end - it doesnt work :( 

我解决了我的问题,这个解决方案很好,但是当我度假时我得到了一组哈希,并且我使用了一套哈希的year_before,这是一个愚蠢的错误,我很抱歉,并感谢您的帮助

1 个答案:

答案 0 :(得分:0)

要获取值,您可以尝试这样:

h = params[:form_holiday]
h.each do |key, value|
  value.values.each do |v|
    puts v # v are the values for 1,2,3 etc
  end
end

如果你想同时获得关键和价值,你可以这样做:

h = params[:form_holiday]
h.each do |key, value|
  value.each do |k, v|
    puts k # k is the key, which would be 1 or 2 or 3 etc.
    puts v # v are the values for 1 or 2 or 3 etc respectively.
    # any operation you perform on k,v
  end
end