迭代哈希,将一行中的所有值作为字符串返回

时间:2011-04-05 04:57:10

标签: ruby hash loops

我有以下哈希:

{"a"=>2, "d"=>5, "f"=>1, "g"=>1, "h"=>1, "i"=>1, "z"=>2}

在ruby中,如何遍历哈希以显示a2d5f1g1h1i1z2

3 个答案:

答案 0 :(得分:2)

无需迭代。 Array#join将以递归方式工作,并且flatten不是必需的。

{"a"=>2, "d"=>5, "f"=>1, "g"=>1, "h"=>1, "i"=>1, "z"=>2}.to_a.join
# => a2d5f1g1h1i1z2

require 'benchmark'
h = {"a"=>2, "d"=>5, "f"=>1, "g"=>1, "h"=>1, "i"=>1, "z"=>2}
n = 1000000
Benchmark.bm do |x|
  x.report('to_a'){n.times{h.to_a.join}}
  x.report('flatten'){n.times{h.flatten.join}}
end

      user     system      total        real
to_a  5.510000   0.000000   5.510000 (  5.509186)
flatten  6.200000   0.000000   6.200000 (  6.219246)

答案 1 :(得分:2)

以下是一对夫妇:

> {"a"=>2, "d"=>5, "f"=>1, "g"=>1, "h"=>1, "i"=>1, "z"=>2}.flatten.join
 => "a2d5f1g1h1i1z2"
> {"a"=>2, "d"=>5, "f"=>1, "g"=>1, "h"=>1, "i"=>1, "z"=>2}.inject('') {|s,v| s << "#{v.join}"}
 => "a2d5f1g1h1i1z2"

答案 2 :(得分:1)

>> {"a"=>2, "d"=>5, "f"=>1, "g"=>1, "h"=>1, "i"=>1, "z"=>2}.flatten.join
=> "a2d5f1g1h1i1z2"