class Array
def self.wrap(object)
Thus, in this case the behavior is different for +nil+, and the differences with
which returns [nil] for +nil+, and calls to Array(object) otherwise.
[*object]
There's also a related idiom that uses the splat operator:
Array.wrap("foo\nbar") # => ["foo\nbar"]
Array("foo\nbar") # => ["foo\n", "bar"], in Ruby 1.8
Array.wrap(:foo => :bar) # => [{:foo => :bar}]
Array(:foo => :bar) # => [[:foo, :bar]]
The last point is particularly worth comparing for some enumerables:
* It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array.
raises an exception, while Array.wrap does not, it just returns the value.
* If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, Kernel#Array
such a +nil+ right away.
moves on to try +to_a+ if the returned value is +nil+, but Arraw.wrap returns
* If the argument responds to +to_ary+ the method is invoked. Kernel#Array
This method is similar in purpose to Kernel#Array, but there are some differences:
Array.wrap(0) # => [0]
Array.wrap([1, 2, 3]) # => [1, 2, 3]
Array.wrap(nil) # => []
* Otherwise, returns an array with the argument as its single element.
* Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned.
* If the argument is +nil+ an empty list is returned.
Specifically:
Wraps its argument in an array unless it is already an array (or array-like).
def self.wrap(object) if object.nil? [] elsif object.respond_to?(:to_ary) object.to_ary else [object] end end