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'
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