1

I have an array like this

data = [ { "email"=>"[email protected]", "id"=>001, "name"=>"Name 1" }, { "email"=>"[email protected]", "id"=>002, "name"=>"Name 2" }, ] 

and I want to select by name

name = data.select {|x| x[:name] == "Name 1"} 

the result is

[ { "email"=>"[email protected]", "id"=>001, "name"=>"Name 1" } ] 

And I get what I want, but what if I want to just get the id?

I expect results like this: 001

1 Answer 1

3

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:

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:

data.select { |x| x['name'] == 'Name 1' }.map { |x| x['id'] } # [1] 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.