如何从 Ruby 中的哈希表中获取第一个键值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12880770/
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:27:16  来源:igfitidea点击:

How to get the first key and value pair from a hash table in Ruby

rubyhash

提问by Xitcod13

I'm trying to get the first key and value key from a hash table in ruby. I don't know the key values of the hash because it is passed to the method. I cant find anywhere online how to find the first key/value as a separate hash table. I think hash[0]will just try to find an element with a name 0 it just returns nilwhen I run the code.

我正在尝试从 ruby​​ 中的哈希表中获取第一个键和值键。我不知道散列的键值,因为它被传递给方法。我在网上找不到任何地方如何找到第一个键/值作为单独的哈希表。我认为hash[0]只会尝试查找名称为 0 的元素,它会nil在我运行代码时返回。

I know I can find the key name and the value and then create a new hash from them but i wonder if there is an easier way to do this so I get a hash right away.

我知道我可以找到键名和值,然后从它们创建一个新的散列,但我想知道是否有更简单的方法来做到这一点,所以我马上得到一个散列。

here is my code:

这是我的代码:

def rps_game_winner(game)

rock_in_hash = game.invert['R']
paper_in_hash = game.invert['P']
scissors_in_hash = game.invert['S']

if(rock_in_hash)
      if(paper_in_hash)
        return paper_in_hash;
      elsif(scissors_in_hash)
        return rock_in_hash
      end
    elsif(paper_in_hash)
      if(rock_in_hash)
        return paper_in_hash
      elsif(scissors_in_hash)
        return scissors_in_hash
      end
    end
        key = game.keys[-1]
        value = game.values[-1]
            winner = {key => value}
    return winner 
    end

game_one = { "Bob" => 'P', "Jim" => 'P' }

puts rps_game_winner(game_one)

This gets me the correct result the problem is I don't understand why it's -1 instead of zero... And i was hoping there was a better way to get the first key/value pair of a hash table instead of creating new hash table with the key and value you retrieved from the previous table.

这让我得到了正确的结果问题是我不明白为什么它是 -1 而不是零......而且我希望有更好的方法来获取哈希表的第一个键/值对而不是创建新的哈希包含您从上一个表中检索到的键和值的表。

回答by pguardiario

You can just do

你可以做

key, value = hash.first

or if you prefer:

或者,如果您更喜欢:

key = hash.keys[0]
value = hash.values[0]

Then maybe:

那么也许:

new_hash = {key => value}

回答by metakungfu

There is a shorter answerthat does not require you to use extra variables:

有一个较短的答案,不需要您使用额外的变量:

h = { "a" => 100, "b" => 200 , "c" => 300, "d" => 400, "e" => 500}
Hash[*h.first] #=> {"a" => 100}

Or if you want to retrieve a key/value at a any single position

或者,如果您想在任何单个位置检索键/值

Hash[*h.to_a.at(1)] #=> {"b" => 200}

Or retrieve a key/values from a range of positions:

或者从一系列位置检索键/值

 Hash[h.to_a[1,3]] #=> {"b"=>200, "c"=>300, "d"=>400}