如何获得在Ruby中迭代散列的特定输出? [英] How to get a specific output iterating a hash in Ruby?

查看:105
本文介绍了如何获得在Ruby中迭代散列的特定输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我想要迭代的哈希:

  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.each do | key,array | 
puts#{key} -----
puts数组
结束

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


I want to get a specific output iterating a Ruby Hash.

This is the Hash I want to iterate over:

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

This is the output I would like to get:

1-----

a

b

2-----

c

3-----

d 

e

f

g

4-----

h

In Ruby, how can I get such an output with my Hash ?

解决方案

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

Regarding order I should add, that in 1.8 the items will be iterated in random order (well, actually in an order defined by Fixnum's hashing function), while in 1.9 it will be iterated in the order of the literal.

这篇关于如何获得在Ruby中迭代散列的特定输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆