如何获取 ruby 哈希中键的索引? [已关闭]

问题描述 投票:0回答:2

自 Ruby 1.9 起,散列保证保留插入顺序,因此迭代顺序是明确定义的。 如何获取哈希中元素的索引?

例如,如果我有

footnotes = { "apple" => "is a fruit", "cat" => "is an animal", "car" => "a transport"}

我怎样才能得到这些的索引?,比如:

footnotes["cat"].index
# => 1
ruby hash
2个回答
11
投票

无需先检索密钥:

footnotes.find_index { |k,_| k== 'cat' } #=> 1

关于哈希键值对是否有索引(自 v1.9 起)的问题,我只想指出 Ruby 僧侣决定为我们提供 Enumerable#find_index,这当然意味着

Hash.instance_methods.include?(:find_index) #=> true


4
投票

你可以做

footnotes.to_a.index {|key,| key == 'cat'}
# => 1
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.