Reputation: 191
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
Reputation: 110675
csv.reduce(&:merge).keys
#=> [:fruit, :number, :age, :name]
Just sayin'
Upvotes: 3
Reputation: 116710
Without braces or pipes:
csv.flat_map(&:keys).uniq
or:
csv.map(&:keys).flatten.uniq
Upvotes: 0
Reputation: 37409
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