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

Creating an HTTP Streaming Client in Silverlight

The Order of Rails Validation Filters

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