简体   繁体   中英

how to get hash values by position in ruby?

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.

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]]

You can extend Hash to get what you need follows (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

Simply like this:

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

But the order of elements are undefined, maybe they are not in the order you would like to get them.

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

Hash values can only by accessed by keys as explained in other answers. The index property of arrays is not supported in hashes. If you want to use a ordered hash in ruby you can use ActiveSupport::OrderedHash, but i don't think you are looking for this feature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM