[英]How do I get a specific array index in ruby?
I have an array like this我有一个这样的数组
data = [
{
"email"=>"name1@mail.com",
"id"=>001,
"name"=>"Name 1"
},
{
"email"=>"name2@mail.com",
"id"=>002,
"name"=>"Name 2"
},
]
and I want to select by name我想按名称 select
name = data.select {|x| x[:name] == "Name 1"}
the result is结果是
[
{
"email"=>"name1@mail.com",
"id"=>001,
"name"=>"Name 1"
}
]
And I get what I want, but what if I want to just get the id?我得到了我想要的,但是如果我只想得到 id 怎么办?
I expect results like this: 001
我期望这样的结果:001
There are different ways to get what you need, depending on the scenario in which you are.根据您所处的场景,有不同的方法可以得到您需要的东西。
If you need only the id
key/value from a single object, you can use find
:如果您只需要来自单个 object 的
id
键/值,则可以使用find
:
data.find { |x| x['name'] == 'Name 1' }['id']
# 1
In the other hand, if you need more than one, and using select
you filter them, then you can map the id
from every resulting object:另一方面,如果您需要多个,并使用
select
过滤它们,那么您可以 map 来自每个生成的 object 的id
:
data.select { |x| x['name'] == 'Name 1' }.map { |x| x['id'] }
# [1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.