Rails spilt hash
H开发者_运维技巧ow, if it's possible, can I split this hash:
{2011=>["46", "47", "48", "49"]}
Into
46
47
48
49
So I get four separate records to work with. Thanks...
You can iterate over it with each.
years = {2011=>["46", "47", "48", "49"]}
years.each do |year, values|
values.each do |value|
puts value
end
end
#=> 46
#=> 47
#=> 48
#=> 49
my_hash = {2011=>["46", "47", "48", "49"]}
element1, element2, element3, element4 = my_hash[2011]
so
element1
#=> "46"
element4
#=> "49"
# ETC
This?
ruby-1.9.2-p180 :005 > years = {2011=>["46", "47", "48", "49"]}
=> {2011=>["46", "47", "48", "49"]}
ruby-1.9.2-p180 :006 > years.values.flatten
=> ["46", "47", "48", "49"]
Flatten simply makes one-dimensional array in case you have multiple years.
http://www.ruby-doc.org/core/classes/Hash.html
精彩评论