我如何迭代数组的哈希值

时间:2014-07-07 22:31:22

标签: ruby arrays hash

我是ruby的新手,想知道如何迭代这个数组中的以下哈希。

这是我的代码:

x = {:country => "china", :people=>'chinese'}
y = {:country => "india", :people=>'indians'}
z = {:country => "iran", :people=>'iranians'}

countries = [x, y, z]

我想让我的代码吐出来:

'你有3个国家'

第一个名字是:china 第二个名字是:印度 第三个名字是伊朗

2 个答案:

答案 0 :(得分:1)

我认为你的意思是:

x = {:country => "china", :people=>'chinese'}
y = {:country => "india", :people=>'indians'}
z = {:country => "iran", :people=>'iranians'}

countries = [x, y, z]

如果是这样,你可以通过

来计算
puts "You have #{countries.size}"

您可以执行以下每个国家/地区名称输出:

countries.each_with_index do |country, index|
  puts "#{index}. #{country[:country]}"
end

答案 1 :(得分:1)

x = {:country => "china", :people=>'chinese'}
y = {:country => "india", :people=>'indians'}
z = {:country => "iran", :people=>'iranians'}

countries = [x, y, z]

countries.each.with_index(1) do |value, index|
   puts "The name of country #{index} is #{value[:country]}"
end