关于Ruby collect方法的问题 [英] Question on Ruby collect method
问题描述
我有一个哈希数组
例如:
cars = [{:company => "Ford", :type => "SUV"},
{:company => "Honda", :type => "Sedan"},
{:company => "Toyota", :type => "Sedan"}]
# i want to fetch all the companies of the cars
cars.collect{|c| c[:company]}
# => ["Ford", "Honda", "Toyota"]
# i'm lazy and i want to do something like this
cars.collect(&:company)
# => undefined method `company'
我想知道是否有类似的快捷方式来执行上述操作.
I was wondering if there is a similar shortcut to perform the above.
推荐答案
我相信你当前的代码 cars.collect{|c|如果您要枚举任意数组,c[:company]}
是最好的方法.您将通过 & 传入的方法快捷方式必须是在 Hash 上定义的方法,因为数组中的每个对象都是 Hash
类型.由于没有为 Hash
定义 company
方法,您会收到未定义方法 'company'"错误.
I believe your current code cars.collect{|c| c[:company]}
is the best way if you're enumerating over an arbitrary array. The method you would pass in via the & shortcut would have to be a method defined on Hash since each object in the array is of type Hash
. Since there is no company
method defined for Hash
you get the "undefined method 'company'" error.
如果您正在对汽车数组进行操作,则可以使用 cars.collect(&:company)
,因为传递到 collect
块的每个对象都将是Car
类型(具有可用的公司方法).因此,也许您可以修改您的代码,以便改用 Cars 数组.
You could use cars.collect(&:company)
if you were operating on an Array of Cars though, because each object passed into the collect
block would be of type Car
(which has the company method available). So maybe you could modify your code so that you use an array of Cars instead.
这篇关于关于Ruby collect方法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!