2014-07-07 84 views
-2

我是ruby的新手,想了解如何通过下面的散列来遍历此数组。如何迭代数组的散列

这里是我的代码:

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

countries = [x, y, z] 

我想为我的代码吐出:

'你有3个国家的

的第一个名字是:中国 第二个名字是:印度 第三个名字是伊朗

+0

什么是'了''B',' c','d'?它们与这个问题有什么关系?关于这三个国家的信息来自哪里?你想收集所有的类是散列的局部变量?或者,名称是属于字母表后半部分的单个字母的所有局部变量? – sawa

回答

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 
+0

谢谢安东尼,这非常有帮助。 – visBar

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