Ruby unlike for example JavaScript or PHP enforces the number of arguments a method is called with:
def foo(a,b)
end
So if you call foo
with no arguments Ruby will raise an exception ArgumentError: wrong number of arguments (0 for 2)
.
By setting a default value, you mark a argument as optional:
def foo(a = nil, b = nil)
end
Calling foo
with no arguments will no longer raise an error.
This is often used to create methods that can take list arguments or a hash:
def foo(a = nil, b = nil, opts = {})
opts.each do |k,v|
puts "#{k} : #{v}"
end
end
As to why Ruby does this - its a language design decision. It does in many cases help track down simple bugs where you are simply passing the wrong arguments. In a language that does not enforce this you would get a type or undefined error from inside the method which is harder to spot the root cause of. IMHO Matz got this one right.