17

Noob question here!

I have an array with hashes that looks like this:

arr = [{id: 1, name: "Pedro"},{id: 2, name: "Pablo"}]

and want to have an array like this:

ids = [1,2]

I looked into using map or select like this:

ids = arr.each.select{|k,v| "id"==k}

But I can't figure it out.

0

1 Answer 1

31

Try the following:

ids = arr.map { |x| x[:id] }
Sign up to request clarification or add additional context in comments.

3 Comments

@Cycle: Several reasons: First :[ is not a symbol, because [ is not a valid identifier. Secondly, you cannot use the & trick in conjunction with method arguments, because the precise syntax is method(arg1, arg2, ..., &x), where x is an expression that evaluates to a value that has a to_proc method. That to_proc method is called and the resulting Proc object passed as the block parameter to method.
That's fine. I need to retrieve more than one value for example (id and name). Will it possible?
@sasikkumare why would it not be possible?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.