我有一个散列数组,在数组中有不同的键:
csv = [{:fruit=>"apple", :number=>23},{:age=>12,:name=>"XYZ"}]
如何获得这样的所有密钥:
[:fruit,:number,:age,:name]
我试过
array = csv.collect {|key,value| key }
答案 0 :(得分:5)
./bin/storm jar examples/storm-starter/storm-starter-topologies-0.9.3.jar storm.starter.WordCountTopology TOne
Failed with error: Error: Could not find or load main class storm.starter.WordCountTopology
Running from directory examples/storm-starter
/root/storm/apache-storm-0.10.0/bin/storm jar storm-starter-topologies-0.10.0.jar storm.starter.WordCountTopology TOne
如果某些密钥有多个实例,并且您希望每个密钥只有一次,则还应添加uniq
:
csv.flat_map { |a| a.keys }
# => [:fruit, :number, :age, :name]
答案 1 :(得分:3)
csv.reduce(&:merge).keys
#=> [:fruit, :number, :age, :name]
只是说'
答案 2 :(得分:0)
没有大括号或管道:
csv.flat_map(&:keys).uniq
或:
csv.map(&:keys).flatten.uniq