7

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.

4

6 回答 6

11

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

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

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

于 2012-08-28T08:52:31.517 回答
5

Well the position is something that is not very well defined in a hash as by definition it is an unordered set. Still if you insist of being able to do such a thing you can convert the hash to array and then proceed the way you know:

irb(main):001:0> h = {:a => 1, :b => 2}
=> {:b=>2, :a=>1}
irb(main):002:0> h.to_a
=> [[:b, 2], [:a, 1]]
于 2012-08-28T08:26:59.120 回答
2

您可以扩展 Hash 以获得您需要的内容(ruby 1.9.x):

class Hash
  def last                # first is already defined
    idx = self.keys.last
    [idx , self[idx]]
  end
  def array_index_of(n)   # returns nth data
    idx = self.keys[n]
    self[idx]
  end
end

h = {"a" => 100, "b" => 200}
h.first # ["a", 100]
h.last  # ["b", 200]

h.array_index_of(0) # => 100
h.array_index_of(1) # => 200
于 2013-03-22T17:40:52.087 回答
1

就像这样:

h.values[0]
# or
h.keys[0]

但是元素的顺序是不确定的,也许它们不是你想要的顺序。

于 2012-08-28T08:28:06.313 回答
0

You can get elements only by keys. Hash is a structure where there is no order, like in a set.

于 2012-08-28T08:27:26.247 回答
0

哈希值只能通过键访问,如其他答案中所述。哈希不支持数组的索引属性。如果你想在 ruby​​ 中使用有序哈希,你可以使用 ActiveSupport::OrderedHash,但我认为你不是在寻找这个功能。

于 2012-08-28T08:43:41.010 回答