如何获取哈希的密钥

时间:2022-03-01 10:46:39

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.

我想得到钥匙,所以我可以在值旁边的表格中显示它。

2 个解决方案

#1


1  

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.

等等。

#2


2  

You can iterate over a hash using:

您可以使用以下方法迭代哈希:

data.each do |key, value|

end

#1


1  

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.

等等。

#2


2  

You can iterate over a hash using:

您可以使用以下方法迭代哈希:

data.each do |key, value|

end