John Rees
John Rees

Reputation: 1813

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.

Upvotes: 4

Views: 1212

Answers (3)

Daniel Rikowski
Daniel Rikowski

Reputation: 72544

It's the Kernel#Array method, as others have already stated.

But the Ruby documentation does not give credit to this method's usefulness in simplifying your code. Also it does not tell you that objects which don't have a to_ary or a to_a method are encapsulated in an array.

Array([1,2,3])        -> [1,2,3]
Array(1..3)           -> [1,2,3]
Array({ a: 1, b: 2 }) -> [[:a, 1],[:b,2]]
Array("Hello World")  -> ["Hello World"]
Array(1)              -> [1]

All these features of Kernel#Array allow you to handle typical corner cases with parameters in one single line.

See this code, which is a typical situation in many APIs or DSLs:

# data can be nil, a single value or an array
def handle(data)
  data ||= Array.new   #Case 1: Data is nil
  data = [data] unless data.is_a?(Array)   #Case 2: Data is a single value
  data.each { |d| ... }
end

This can be simplified by using Kernel#Array:

def handle(data)
  Array(data).each { |d| ... }
end

Of course one has to be careful with providing different types for the data parameter, because the to_ary/to_a methods might or might not give you what you expect.

Upvotes: 2

AShelly
AShelly

Reputation: 35600

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]  

Upvotes: 2

Brian Carper
Brian Carper

Reputation: 73006

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.)

Upvotes: 13

Related Questions