如何获得由数字索引的哈希值(How to get a hash value by numeric i

2019-08-17 05:06发布

有一个哈希:

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

可以参考我的哈希值:

h[:a], h[:c]

但我想通过数字索引来参考:

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

可能吗?

Answer 1:

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

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


Answer 2:

h.values会给你要求的数组。

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

UPD而有了答案h[h.keys[0]]被标记为正确的,我有点有点好奇与基准:

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)

看起来我们对生产力的10%随地吐痰。



Answer 3:

因此,你需要两个数组索引和散列索引?

如果你只需要第一个,使用一个数组。

否则,你可以做到以下几点:

h.values[0]
h.values[1]


文章来源: How to get a hash value by numeric index
标签: ruby hash