红宝石:从一个值对象的数组新数组 [英] Ruby: new array from one value in an array of objects
本文介绍了红宝石:从一个值对象的数组新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
原谅我,如果这已经被问,我找不到它。
Forgive me if this has already been asked, I couldn't find it.
我有对象的数组,如:
[<#Folder id:1, name:'Foo', display_order: 1>,
<#Folder id:1, name:'Bar', display_order: 2>,
<#Folder id:1, name:'Baz', display_order: 3>]
我想这个数组转换为数组刚的名字,如:
I'd like to convert that array into an array just of the names, like:
['Foo','Bar','Baz']
和,而我在这这将是很好,如果我可以使用相同的技术在道路上创建两个参数的数组,即名称,显示顺序将如下所示:
and, while I'm at it it would be nice if I could use the same technique down the road to create an array from two of the parameters, ie name and display order would look like:
[['Foo',1],['Bar',2],['Baz',3]]
什么是最好的Ruby之道做这种事情?
What's the best 'Ruby Way' to do this kind of thing?
谢谢!
推荐答案
这些怎么样?
# ['Foo','Bar','Baz']
array = folders.map { |f| f.name }
# This does the same, but only works on Rails or Ruby 1.8.7 and above.
array = folders.map(&:name)
# [['Foo',1],['Bar',2],['Baz',3]]
array = folders.map { |f| [f.name, f.display_order] }
这篇关于红宝石:从一个值对象的数组新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文