What ruby ​​method call is array (x)

What is the point and where is the Ruby documentation for the syntax:

Array(phrases) 

which I found to view 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 Array.new is usually used to create an array, so something else should happen here. BTW from the context of this code, the phrases variable can be either a string or an array of strings.

+4
source share
3 answers

Most likely, the Kernel#Array method, see here . It is slightly different from Array.new ; it is more of a throw to an array. (He is trying to_ary and to_a .)

+13
source

Array (x) seems to act exactly like x.to_a.

@Brian is right - this is a kernel method. Pickax says:

Array (arg) β†’ anArray

Returns arg.to_a.

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

This is the Kernel#Array method, as others have already pointed out.

But the Ruby documentation does not take into account the usefulness of this method to simplify the code. Nor does it tell you that objects that do not have a to_ary or to_a 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 of these Kernel#Array functions allow you to handle typical corner cases with parameters on the same line.

See this code, which is typical of 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 using Kernel#Array :

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

Of course, you need to be careful about providing different types for the data parameter, because the to_ary / to_a may or may not give you what you expect.

+2
source

All Articles