Ruby 获取类的唯一数组
我有一个对象数组:Ruby 获取类的唯一数组,ruby,ruby-on-rails-3,Ruby,Ruby On Rails 3,我有一个对象数组: @searches 它可能会返回如下结果: --- !ruby/object:Profile attributes: id: 2 name: Basti Stolzi username: paintdat website: '' biography: '' created_at: 2013-06-10 19:51:29.000000000 Z updated_at: 2013-06-15 10:10:17.000000000 Z user_i
@searches
它可能会返回如下结果:
--- !ruby/object:Profile
attributes:
id: 2
name: Basti Stolzi
username: paintdat
website: ''
biography: ''
created_at: 2013-06-10 19:51:29.000000000 Z
updated_at: 2013-06-15 10:10:17.000000000 Z
user_id: 2
--- !ruby/object:Essential
attributes:
id: 4
description: ! '#paintdat'
user_id: 1
created_at: 2013-06-16 08:19:47.000000000 Z
updated_at: 2013-06-16 08:19:47.000000000 Z
photo_file_name: Unknown-1.jpeg
photo_content_type: image/jpeg
photo_file_size: 101221
photo_updated_at: 2013-06-16 08:19:46.000000000 Z
--- !ruby/object:Essential
attributes:
id: 3
description: ! '@user_mention_2 well done! #paintdat'
user_id: 1
created_at: 2013-06-16 07:56:55.000000000 Z
updated_at: 2013-06-16 08:00:24.000000000 Z
photo_file_name: Unknown.jpeg
photo_content_type: image/jpeg
photo_file_size: 135822
photo_updated_at: 2013-06-16 07:56:55.000000000 Z
现在,我想在该数组中获得一个唯一的类数组,如:
--- !ruby/class 'Profile'
--- !ruby/class 'Essential'
如果没有两个循环,这将是很好的。希望有人能帮我 我建议您执行映射和唯一的可枚举运算符来执行此操作。您的代码如下(取决于从单个元素中选择类所需的内容): 有关更多信息,请查看和上的文档 编辑: 注:使用
&
运算符(将符号转换为过程)可以更简洁地说明上述内容:
“AndreZimpel,如果它工作,你应该考虑接受这个答案是正确的。”ZeangSoi,是的,我必须等待6分钟。你可以缩短代码使用<代码> @搜索。地图((类:)。UNIQ < /代码>。@ TROO2K好点,我编辑了原来的答案,包括你的建议。
@searches.map{ |search| search.class }.uniq
@searches.map(&:class).uniq