why Array.wrap ?

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
    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
      if object.respond_to?(:to_ary)

IIRC, it's different on 1.9.

There's also:


=> [[:a, :b]]

Mighty annoying.

Ah I tried as well with same result:

[xnoria@ruby-versions ~]$ irb191
irb(main):001:0> Array(nil)
=> []
irb(main):002:0> Array(0)
=> [0]
irb(main):003:0> Array([0])
=> [0]
irb(main):008:0* class C
irb(main):009:1> def to_ary
irb(main):010:2> [0]
irb(main):011:2> end
irb(main):012:1> end
=> nil
irb(main):013:0> Array(C.new)
=> [0]

IIRC, it's different on 1.9.

I don't think its a 1.9 thing. It had something to do with strings
being treated as Enumerable. See this:

Array("helo \n world")

=> ["helo \n", " world"]

Array.wrap("helo \n world")

=> ["helo \n world"]


Array("foo\nbar") # => ["foo\n", "bar"]

Array.wrap("foo\nbar") # => ["foo\nbar"]


Array() does too much. We want a uniform wrapper with no surprises.


Ah yes, Array() calls #to_a also.

Excellent I'll the hash example and those to the RDoc and AS guide.


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.

Ugh sorry, Flanagan.

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.