大多数Rubyish方法从一个对象数组中获取包含特定值的数组?

Ale*_*lex 6 ruby arrays

我有一组ruby对象,看起来像这样:

[#<email: "someemail" other_properties: "SDFDF">, #<...>, #<...>]
Run Code Online (Sandbox Code Playgroud)

数组中的每个对象都有一个email属性.我想获得数组中ruby对象的所有电子邮件属性的新数组.

执行代码后,我会有一个如下所示的数组:

["email@example.com", "anotheremail@gmail.com", ...] 
Run Code Online (Sandbox Code Playgroud)

我比红宝石更新,并希望以最红宝石的方式做到这一点.

我的问题是,在ruby中执行此操作的最佳方法是什么?

Bri*_*ell 16

您可以使用该map方法将块应用于数组的每个元素,返回包含每个调用结果的新数组:

somearray.map {|x| x.email}
Run Code Online (Sandbox Code Playgroud)

  • 在Ruby 1.87+中,您可以将其简化为`somearray.map(&:email)` (8认同)