如何在ruby中按位置获取散列值? [英] how to get hash values by position in ruby?

查看:107
本文介绍了如何在ruby中按位置获取散列值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:
h = Hash [a= > 100,b=> 200]



在这个数组中,当我们调用h [0]时,它返回给定数组中的第一个元素。 b

哈希中可能有同样的东西吗?如果是这样,那么怎么样?



在此先感谢,
Prasad。

解决方案

如上所述,根据您的使用情况,您可以这样做:

  h.keys [0] 
h.values [0]
h.to_a [0]



<由于Ruby 1.9.1 Hash 保留了插入顺序。如果您需要兼容Ruby 1.8 ActiveSupport :: OrderedHash 是一个不错的选择。


I want to get hash values by position like an array.

Example: h = Hash["a" => 100, "b" => 200]

In this array when we call h[0], it returns first element in given array.

That same thing possible in hash? If it is, then how ?

Thanks in Advance, Prasad.

解决方案

As mentioned above, depending on your use case, you can do this with:

  h.keys[0]
  h.values[0]
  h.to_a[0]

Since Ruby 1.9.1 Hash preserves the insertion order. If you need Ruby 1.8 compatibility ActiveSupport::OrderedHash is a good option.

这篇关于如何在ruby中按位置获取散列值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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