Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve specific values from hashes within an array ruby rails

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.

like image 407
obi Avatar asked Mar 23 '12 19:03

obi


1 Answers

Try the following:

ids = arr.map { |x| x[:id] }
like image 166
Niklas B. Avatar answered Oct 29 '22 18:10

Niklas B.