开发者

Rails spilt hash

开发者 https://www.devze.com 2023-03-25 13:02 出处:网络
H开发者_运维技巧ow, if it\'s possible, can I split this hash: {2011=>[\"46\", \"47\", \"48\", \"49\"]}

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号