如何将单个对象转换为ruby中的Enumerable

Kyl*_*oon 2 ruby

我有一个方法可以返回单个对象或对象集合.我希望能够在该方法的结果上运行object.collect,无论它是否是单个对象或集合.我怎样才能做到这一点?

profiles = ProfileResource.search(params)
output = profiles.collect do | profile |
    profile.to_hash
end
Run Code Online (Sandbox Code Playgroud)

如果配置文件是单个对象,当我尝试在该对象上执行collect时,我会收到NoMethodError异常.

Mik*_*ffe 6

小心使用展平方法,如果search()返回嵌套数组,则可能会导致意外行为.

profiles = ProfileResource.search(params)
profiles = [profiles] if !profiles.respond_to?(:collect)
output = profiles.collect do |profile|
    profile.to_hash
end
Run Code Online (Sandbox Code Playgroud)


小智 6

这是一个班轮:

[*ProfileResource.search(params)].collect { |profile| profile.to_hash }
Run Code Online (Sandbox Code Playgroud)

诀窍是splat(*)将单个元素和枚举变为参数列表(在本例中为新数组运算符)