from actual parameter of type array to formal parameter of list in Ruby

I was curious what * (star) means in front of a method parameter. Here is the result:

def xyz(*arr)
arr.each do |a|
puts a.class
end
end

$xyz 1,2,3
=> Fixnum, Fixnum, Fixnum
$xyz [1,2,3]
=> Array
$xyz *[1,2,3]
=> Fixnum, Fixnum, Fixnum

Therefore, for example,

attribute_names = 'name', 'age', 'phone_number' #creates an array
attr_accessor *attribute_names

is equivalent to

attr_accessor 'name', 'age', 'phone_number'

Comments

Popular posts from this blog

Accessing Resources in Java, use of getResource method of Class and ClassLoader, How to access test data in unit tests

Comparison of equality operators in Ruby: == vs. equal? vs. eql? vs. ===

TCPView