简体   繁体   English

使用多个值访问 ruby hash 中的特定值

[英]Access a specific value in ruby hash with multiple values

Hi how can I access a specific value in ruby hash, for example how can i get "colder" inside jupiter嗨,我怎样才能访问 ruby hash 中的特定值,例如我怎样才能在木星内部获得“更冷”

planets= {
"jupiter" => ["brown", "big" , "colder"]
"mars" => ["red", "small", "cold"]
};

Focus on Intent专注于意图

There's definitely more than one way to do this, so the key is to focus less in the result (although getting the right result is important) and more on effectively expressing your intent with the code.肯定有不止一种方法可以做到这一点,所以关键是少关注结果(尽管获得正确的结果很重要),而更多地关注用代码有效地表达你的意图 All of the examples provided below (and others besides) will give you the right result, but the approach and semantics are all slightly different.下面提供的所有示例(以及其他示例)都会为您提供正确的结果,但方法和语义都略有不同。 Always pick the approach that most closely matches what you're trying to say.始终选择与您要表达的内容最接近的方法。

Fix Your Hash修复您的 Hash

Before doing anything else, fix your invalid hash.在做任何其他事情之前,请修复您无效的 hash。 For example:例如:

planets = {
  "jupiter" => ["brown", "big", "colder"],
  "mars"    => ["red", "small", "cold"],
}

Positional Selection位置选择

Select your key, then the last element. Select 您的密钥,然后是最后一个元素。 Examples include:示例包括:

planets['jupiter'][2]
#=> "colder"

planets['jupiter'][-1]
#=> "colder"

planets['jupiter'].last
#=> "colder"

Content-Based Selection基于内容的选择

If you don't know which element you want to select from the nested array, you'll need to use some form of matching to find it.如果您不知道要从嵌套数组中找到 select 的哪个元素,则需要使用某种形式的匹配来找到它。 Examples can include:示例可以包括:

planets['jupiter'].grep(/colder/).pop
#=> "colder"

planets['jupiter'].grep(/colder/).first
#=> "colder"

planets['jupiter'].grep(/colder/)[0]
#=> "colder"

planets['jupiter'].select { _1.match? /colder/ }.pop
#=> "colder"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM