Palak Chaudhary
Palak Chaudhary

Reputation: 191

Finding keys of an array of hash

I have an array of hash with different keys across the array:

csv = [{:fruit=>"apple", :number=>23},{:age=>12,:name=>"XYZ"}]

How do I get all the keys like this:

[:fruit,:number,:age,:name]

I tried

array = csv.collect {|key,value| key }

Upvotes: 0

Views: 62

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

csv.reduce(&:merge).keys
  #=> [:fruit, :number, :age, :name]

Just sayin'

Upvotes: 3

peak
peak

Reputation: 116710

Without braces or pipes:

csv.flat_map(&:keys).uniq

or:

csv.map(&:keys).flatten.uniq

Upvotes: 0

Uri Agassi
Uri Agassi

Reputation: 37409

Try using flat_map with keys:

csv.flat_map { |a| a.keys }
# => [:fruit, :number, :age, :name]

If there are multiple instances of some keys, and you want to have each key only once, you should also add uniq:

csv = [{:fruit=>"apple", :number=>23},{:age=>12,:name=>"XYZ", :number=>11}]
array = csv.flat_map { |a| a.keys }
# => [:fruit, :number, :age, :name, :number]
array.uniq
# => [:fruit, :number, :age, :name]

Upvotes: 5

Related Questions