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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With