如何获取在Ruby中迭代哈希的特定输出?

我希望得到一个迭代Ruby Hash的特定输出 .

这是我想迭代的哈希:

hash = {
  1 => ['a', 'b'], 
  2 => ['c'], 
  3 => ['d', 'e', 'f', 'g'], 
  4 => ['h']
}

这是我想得到的输出:

1-----

a

b

2-----

c

3-----

d 

e

f

g

4-----

h

在Ruby中,如何使用Hash获得这样的输出?

回答(6)

2 years ago

hash.each do |key, array|
  puts "#{key}-----"
  puts array
end

关于我应该添加的顺序,在1.8中,项目将以随机顺序迭代(好吧,实际上是按照Fixnum的散列函数定义的顺序),而在1.9中,它将按照文字的顺序迭代 .

2 years ago

迭代哈希的最基本方法如下:

hash.each do |key, value|
  puts key
  puts value
end

2 years ago

hash.keys.sort.each do |key|
  puts "#{key}-----"
  hash[key].each { |val| puts val }
end

2 years ago

在散列上调用sort会将其转换为嵌套数组,然后按键对它们进行排序,因此您只需要:

puts h.sort.map {|k,v| ["#{k}----"] + v}

如果你实际上不需要“----”部分,它可以只是:

puts h.sort

2 years ago

我的一线解决方案:

hash.each { |key, array| puts "#{key}-----", array }

我觉得这很容易阅读 .

2 years ago

你也可以 refine Hash::each 所以它将支持 recursive 枚举 . 这是我的 Hash::eachHash::each_pair )版本,支持 blockenumerator

module HashRecursive
    refine Hash do
        def each(recursive=false, &block)
            if recursive
                Enumerator.new do |yielder|
                    self.map do |key, value|
                        value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
                        yielder << [[key], value]
                    end
                end.entries.each(&block)
            else
                super(&block)
            end
        end
        alias_method(:each_pair, :each)
    end
end

using HashRecursive

这里有 examplesHash::each ,有和没有 recursive 标志:

hash = {
    :a => {
        :b => {
            :c => 1,
            :d => [2, 3, 4]
        },
        :e => 5
    },
    :f => 6
}

p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2

p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6

hash.each do |key, value|
    puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6

hash.each(true) do |key, value|
    puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6

hash.each_pair(recursive=true) do |key, value|
    puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6

以下是问题本身的示例:

hash = {
    1   =>  ["a", "b"], 
    2   =>  ["c"], 
    3   =>  ["a", "d", "f", "g"], 
    4   =>  ["q"]
}

hash.each(recursive=false) do |key, value|
    puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]

另请查看我的递归版 Hash::mergeHash::merge!here .