How to get a hash value by numeric index

29,115

Solution 1

h = {:a => "val1", :b => "val2", :c => "val3"}
keys = h.keys

h[keys[0]] # "val1"
h[keys[2]] # "val3"

Solution 2

h.values will give you an array requested.

> h.values
# ⇒ [
#  [0] "val1",
#  [1] "val2",
#  [2] "val3"
# ]

UPD while the answer with h[h.keys[0]] was marked as correct, I’m a little bit curious with benchmarks:

h = {:a => "val1", :b => "val2", :c => "val3"}
Benchmark.bm do |x|
  x.report { 1_000_000.times { h[h.keys[0]] = 'ghgh'} } 
  x.report { 1_000_000.times { h.values[0] = 'ghgh'} }
end  

#
#       user     system      total        real
#   0.920000   0.000000   0.920000 (  0.922456)
#   0.820000   0.000000   0.820000 (  0.824592)

Looks like we’re spitting on 10% of productivity.

Solution 3

So you need both array indexing and hash indexing ?

If you need only the first one, use an array.

Otherwise, you can do the following :

h.values[0]
h.values[1]
Share:
29,115
Lesha Pipiev
Author by

Lesha Pipiev

Updated on July 09, 2022

Comments

  • Lesha Pipiev
    Lesha Pipiev almost 2 years

    Have a hash:

    h = {:a => "val1", :b => "val2", :c => "val3"}
    

    I can refer to the hash value:

    h[:a], h[:c]
    

    but I would like to refer by numeric index:

    h[0] => val1
    h[2] => val3
    

    Is it possible?

  • Arup Rakshit
    Arup Rakshit over 11 years
    nice explanation :) +1 to you also.
  • Aleksei Matiushkin
    Aleksei Matiushkin over 11 years
    Please see my benchmarks below. Using [h[h.keys[…]] is a bit slow to be the best solution.
  • Sparhawk
    Sparhawk almost 10 years
    @mudasobwa 's solution also makes more sense to me.
  • Arup Rakshit
    Arup Rakshit about 9 years
    Ok.. Thanks for the reply!