Sunday, March 6, 2011

What kind of ruby method call is Array(x)

What is the meaning, and where is the Ruby documentation for the syntax of:

Array(phrases)

which I found browsing the Rails source here:

# File actionpack/lib/action_view/helpers/text_helper.rb, line 109
...
119:           match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')

I thought that Array.new would normally be used to create an array, so something different must be going on here. BTW from the context around this code, the phrases variable can be either a string or an array of strings.

From stackoverflow
  • It's most likely the Kernel#Array method, see here. It's slightly different than Array.new; it's more of a cast into an array. (It tries to_ary and to_a.)

  • Array(x) appears to act exactly the same as x.to_a.

    @Brian is right - it's a method of Kernel. Pickaxe says:

    Array( arg ) -> anArray

    Returns arg .to_a.

    Array(1..5)  » [1, 2, 3, 4, 5]
    

0 comments:

Post a Comment