Chris
Chris

Reputation: 961

How to get the key of a hash

Right now I have a double hash called data like the following:

data [name][action]

ie

 data = {"Mike" => {"Walked" => 13, "Ran" => 5}, "Steve" => {...}}

For this particular hash, I don't actually know the keys in the hash, I just want to iterate over it, like so:

data.each |item| do
    #how to get the key name for item here?
    puts item["Walked"].to_s
    puts item["Ran"].to_s
end

I'd like to get the key so I can display it in a table beside the values.

Upvotes: 0

Views: 103

Answers (2)

Alex.Bullard
Alex.Bullard

Reputation: 5563

You can iterate over a hash using:

data.each do |key, value|

end

Upvotes: 2

dax
dax

Reputation: 11007

You can use each with a key, value syntax, as described in the each documentation:

data.each do |key, values|
  puts key.to_s
  values.each do |value|
    value.to_s
  end
end

You could also use keys or values depending on what you wanted to achieve.

data.keys.each do |key|
  puts key #lists all keys
end

data.values.each do |value|
  puts value #lists all values
end

data.keys.first #first key

and so on.

Upvotes: 1

Related Questions