class Array
def self.wrap(object)
The differences with Kernel#Array explained above
which returns [] for +nil+, but calls to Array(object) otherwise.
[*object]
There's also a related idiom that uses the splat operator:
Array.wrap(foo: :bar) # => [{:foo=>:bar}]
Array(foo: :bar) # => [[:foo, :bar]]
The second point is easily explained with some enumerables:
* It does not call +to_a+ on the argument, but returns an empty array if argument is +nil+.
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
+nil+ right away.
moves on to try +to_a+ if the returned value is +nil+, but Array.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 || [object] else [object] end end