1

ROR Api Dock always starts with a syntax of the method. My example will be link_to:

link_to(name = nil, options = nil, html_options = nil, &block) public

My question is on the "name=nil" or "something = nil" which i see on most every command.

A second example: url_for(options = nil)

Can someone explain what is the point of this or what it is trying to say..does it mean that the option is optional?

Why is it important..

rohin-arka
  • 779
  • 4
  • 10

1 Answers1

1

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.

max
  • 96,212
  • 14
  • 104
  • 165