Ruby:Object.to_a 替换 [英] Ruby: Object.to_a replacement
问题描述
我需要将传入的参数(单个对象或集合)转换为数组.我不知道论据是什么.如果它已经是一个数组,我想离开它,否则从它创建一个单元素数组.我希望 同时允许 method(:objs => obj)
和 method(:objs => [obj1, obj2])
I need to convert a passed in argument (single object or collection) to an Array. I don't know what the argument is. If it is an Array already, I want to leave it, otherwise create a one-element array from it. I'm looking to allow both method(:objs => obj)
and method(:objs => [obj1, obj2])
这似乎是最好的方法(Array#to_a 返回 self):
This seems to be the best way (Array#to_a returns self):
arg = arg.to_a
但是 ruby 文档说Object#to_a
很快就会过时.有方便更换吗?
But the ruby docs say Object#to_a
will soon be obsolete. Is there convenient replacement?
还有比这更简洁的吗?
arg = arg.respond_to?(:to_a) ? arg.to_a : [arg]
推荐答案
使用方法 内核#Array:
Array([1,2,3]) #=> [1, 2, 3]
Array(123) #=> [123]
是的,一开始它可能看起来像一个类,但这实际上是一个以大写字母开头的方法.
Yes it may look like a class at first but this is actually a method that starts with a capital letter.
这篇关于Ruby:Object.to_a 替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!