Partilhar via


Expanding and compressing in Ruby Method calls

2007_0520_184605

One of the things I didn't like in Ruby at all is the support for method overloading. You have no ways to support it in a straight forward way other than to define a single method that takes a variable number of arguments.

 def foo(*f)
  f.each { |a| 
    puts a
  }
end

foo("Hello", "world")

What the above does is that it converts the multiple parameters into a single array and passes it to the method call. I think this is really bad because method overloading is a very basic requirement.

However, Ruby seemed to support another really weird feature of expanding arrays in method calls. What this means is that if a method accepts a number of parameters and it's called with an array then the array is expanded such that the i'th element in the array is passed as the i'th argument.

 def bar(name, address, age)
  puts (name, address, age)
end

details = ["Abhinaba", "Hyderabad, India", 42]
bar(*details)

So details[0] is passed to the name parameter and details[1] is passed as address, and so on

>> Cross posted here

Comments