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

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

问题描述

我想获得迭代 Ruby 哈希的特定输出.

这是我要迭代的哈希:

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

这是我想得到的输出:

1-----一种乙2-----C3-----d电子FG4-----H

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

解决方案

hash.each do |key, array|把#{key}-----"放置数组结尾

关于我应该补充的顺序,在 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天全站免登陆