Can't Understand Why This Works

I have 3 methods:

def add_to_cart

do some stuff

redirect_to_index
end

def empty_cart

do some stuff

redirect_to_index(“your cart was emptied”)
end

def redirect_to_index(msg = nil)
flash[:notice] = msg if msg
redirect_to :action => :index
end

How come the flash notice works if I’m setting msg = nil? For example,
if I’m in empty_cart and pass “your cart was emptied” into
redirect_to_index, it passes through OK. I thought that setting
something equal to nil would remove the value. I’m confused.

Thanks!

Hi –

On Fri, 25 Apr 2008, RoRNoob wrote:

redirect_to_index(“your cart was emptied”)
something equal to nil would remove the value. I’m confused.
What you’ve got there is a default value; it means: Set msg to nil if
and only if there’s no argument supplied when the method is called.

Here’s an example:

def say_word(word = “hello”)
puts “#{word}!”
end

say_word # word will be “hello” (the default value)
say_word(“goodbye”) # word will be “goodbye”

David


Rails training from David A. Black and Ruby Power and Light:
INTRO TO RAILS June 9-12 Berlin
ADVANCING WITH RAILS June 16-19 Berlin
INTRO TO RAILS June 24-27 London (Skills Matter)
See http://www.rubypal.com for details and updates!

AHHHH - OK thanks! I’m going through ADWR 3 beta and it doesn’t
explain that piece.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs