如何遍历哈希

时间:2019-04-18 10:23:14

标签: ruby

花3个多小时来找出问题所在-我无法遍历此哈希:

a = {"begin"=>:washington, "end"=>:briston, "min"=>6, "price"=>3}
{"begin"=>:briston, "end"=>:dallas, "min"=>4, "price"=>2}
{"begin"=>:dallas, "end"=>:tokyo, "min"=>3.5, "price"=>3}

如果我编写此代码:

a.each do |xx|
  puts xx["begin"], xx["end"]
end

我收到

`in `[]': no implicit conversion of String into Integer (TypeError)`

出什么问题了?

1 个答案:

答案 0 :(得分:0)

使其像这样的哈希数组

a = [{"begin"=>:washington, "end"=>:briston, "min"=>6, "price"=>3},{"begin"=>:briston, "end"=>:dallas, "min"=>4, "price"=>2},{"begin"=>:dallas, "end"=>:tokyo, "min"=>3.5, "price"=>3}]  

并遍历它:

a.each { |xx| puts xx['begin'], xx['end'] }  

如果要遍历单个哈希,可以这样做:

a.each { |k,v| puts k.to_s + '-' + v.to_s }  

其中k,v是哈希的key,value对。