Hey Active Support defines Array.wrap (copied below). What's the
difference between that and the Ruby builtin Array() method:
Array(nil) # =>
Array([0]) # => [0]
class C
def to_ary
[0]
end
end
Array(C.new) # => [0]
Array(0) # => [0]
Perhaps it was just an overlook that Array() exists?
-- fxn
class Array
# Wraps the object in an Array unless it's an Array. Converts the
# object to an Array using #to_ary if it implements that.
def self.wrap(object)
case object
when nil
when self
object
else
if object.respond_to?(:to_ary)
object.to_ary
else
[object]
end
end
end
end
I wanted to know the difference because I am documenting it. According
to the Pickaxe and Flanafan & Matz the difference is exactly that
Array.wrap does not call to_a, and those examples depict this.
That's true, for example the return value of Array("foo\nbar") depends
on the Ruby version because strings are not enumerables in 1.9. So you
get ["foo\nbar"] in 1.9, and ["foo\n", "bar"] in 1.8.
So Array.wrap is portable as long as +to_ary+ is portable.