How can I convert an array of hashes to an array of hash values?

I have an array of hashes:

[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}]

How can I convert it to array of values:

["male", "male", "female"]


A generic approach to this that would take into account other possible keys:

list = [{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}]

# Collect the 'sex' key of each hash item in the list.
sexes = list.collect { |e| e['sex'] }

In this case,

[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}].map(&:values).flatten

should work.

It takes an array from each hash, then flatten the nested array.

[{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}].flat_map(&:values)

arr = [{"sex"=>"male"}, {"sex"=>"male"}, {"sex"=>"female"}]

EDIT: As directed by @tadman. Thanks!

Need Your Help

Fastest way to display result of count(*) with mySQL (Preferably in one line)

php mysql mysqli

There are multiple moments where I want to simply show a scalar coming back from a count(*) request but I feel like there's a one-liner I could use to replace that.

Javascript, identifying which window was open,


I am opening multiple windows with, on click.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.