keirozzy
keirozzy

Reputation: 11

What is the point of making an argument an array by default?

Sometimes, when a method needs to be given an array as an argument, I see the method defined like this:

def method(argument = [])
  ... 
end

I don't understand why = [] is used. As far as I can see, it adds nothing. If you did supply an array as an argument, the method would run either way, and if you didn't, it would throw an error either way. Is it just convention? Or is it perhaps a visual aid so the programmer can easily see what type of data a method requires?

Upvotes: 0

Views: 71

Answers (2)

Prakash Murthy
Prakash Murthy

Reputation: 13057

Specifying a default value allows you to call the method with AND without that param.

I have found it helpful while adding a new variable to an existing method. If I specify a default value to the new variable, I don't have to worry about changing the previous calls to that method which have only the previous set of variables. If, however, I am not able to specify a default value for the new variable, I will have to go through the code and hunt down all the method calls, and modify it to include the new variable.

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

If you set default argument here, it won't raise an error if you call this method without arguments:

method
# => []

Upvotes: 4

Related Questions