从ruby中的哈希数组创建数组

时间:2012-10-12 07:29:24

标签: ruby arrays

我有一系列哈希。

  

rabbits = [{:color =>“blue”,:height => 5,:name =>“Charles”},{:color =>“red”,:height => 12, :name =>“Henry”},{:color =>“green”,:height => 7,:name =>“Francis”},{:color =>“purple”,:height = > 3,:name =>“William”}]

如何从这个只有:height的数组创建一个数组?

我尝试过:rabbits.map(&:height)rabbits.map{|i| i.height}但是都没有效果。

目标是height_array = [5, 12, 7, 3]

3 个答案:

答案 0 :(得分:6)

这将有效

rabbits.map{|c| c[:height] }

您尝试将height作为c上的方法的其他两种方法并非如此。

答案 1 :(得分:0)

rabbits.inject([]) {|height,hash| height << hash[:height]}

答案 2 :(得分:0)

arr = cats.collect{|c| c[:cats_age] }
相关问题