andkjaer
andkjaer

Reputation: 4065

Rails spilt hash

How, 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...

Upvotes: 0

Views: 50

Answers (3)

Zach Inglis
Zach Inglis

Reputation: 1257

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

Upvotes: 1

BuGo
BuGo

Reputation: 51

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

Upvotes: 0

fl00r
fl00r

Reputation: 83680

my_hash = {2011=>["46", "47", "48", "49"]}
element1, element2, element3, element4 = my_hash[2011]

so

element1
#=> "46"
element4
#=> "49"
# ETC

Upvotes: 0

Related Questions