Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 929
Durga Prasad Avatar asked Aug 28 '12 08:08

Durga Prasad


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

like image 125
Benedikt Deicke Avatar answered Oct 17 '22 21:10

Benedikt Deicke


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]]
like image 36
Ivaylo Strandjev Avatar answered Oct 17 '22 23:10

Ivaylo Strandjev


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
like image 45
Bryan Colvin Avatar answered Oct 17 '22 21:10

Bryan Colvin


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.

like image 34
Matzi Avatar answered Oct 17 '22 22:10

Matzi