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]
Author by
Lesha Pipiev
Updated on July 09, 2022Comments
-
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 over 11 yearsnice explanation :)
+1
to you also. -
Aleksei Matiushkin over 11 yearsPlease see my benchmarks below. Using
[h[h.keys[…]]
is a bit slow to be the best solution. -
Sparhawk almost 10 years@mudasobwa 's solution also makes more sense to me.
-
Arup Rakshit about 9 yearsOk.. Thanks for the reply!