100, "...">

How to get hash values ​​by position in ruby?

I want to get the hash values ​​at a position similar to an array.

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

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

Is the same possible in a hash? If so, then how?

Thank you Advance, Prasadam.

+6
source share
6 answers

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 maintains the insertion order. If you need compatibility with Ruby 1.8 ActiveSupport::OrderedHash , this is a good option.

+9
source

Well, a position is something that is not well defined in the hash, because by definition it is an unordered set. However, if you insist on being able to do this, you can convert the hash to an array, and then continue your path:

 irb(main):001:0> h = {:a => 1, :b => 2} => {:b=>2, :a=>1} irb(main):002:0> h.to_a => [[:b, 2], [:a, 1]] 
+5
source

You can extend the Hash to get what you need (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 
+2
source

Just:

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

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

+1
source

You can get items only with keys. A hash is a structure in which there is no order, for example, in a collection.

0
source

Hash values ​​can only be accessed using keys, as described in other answers. The index property of arrays is not supported in hashes. If you want to use an ordered hash in a ruby, you can use ActiveSupport :: OrderedHash, but I don't think you are looking for this function.

0
source

Source: https://habr.com/ru/post/923944/


All Articles