我有一个对象数组:
@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'
没有2个循环就可以做到这一点。希望有人能帮助我! < 3
答案 0 :(得分:3)
我建议您执行一个地图和唯一的可枚举运算符来执行此操作。您的代码将类似于(取决于从单个元素中选择类所需的内容):
@searches.map{ |search| search.class }.uniq
有关详细信息,请查看Array和Enumerable
上的文档修改强>
请注意,使用&
运算符(将符号转换为proc)可以更简洁地使用上述内容:
@searches.map(&:class).uniq