ruby 如何通过数字索引获取哈希值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15131234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:47:30  来源:igfitidea点击:

How to get a hash value by numeric index

rubyhash

提问by Lesha Pipiev

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?

是否可以?

回答by Aleksei Matiushkin

h.valueswill give you an array requested.

h.values会给你一个请求的数组。

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

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

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)

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

看起来我们在吐槽 10% 的生产力。

回答by saihgala

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

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

回答by Intrepidd

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]