Lesha Pipiev
Lesha Pipiev

Reputation: 3333

How to get a hash value by numeric index

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?

Upvotes: 30

Views: 33896

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 120990

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.

Upvotes: 38

saihgala
saihgala

Reputation: 5774

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

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

Upvotes: 35

Intrepidd
Intrepidd

Reputation: 20858

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]

Upvotes: 5

Related Questions