# Can't Understand Why This Works

**URL:** <https://www.ruby-forum.com/t/cant-understand-why-this-works/135905>\
**Category:** Rails\
**Created:** [April 26, 2008, 1:56am UTC](https://www.ruby-forum.com/t/cant-understand-why-this-works/135905 "2008-04-26T01:56:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rornoob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/7bcc69/32.png) [@rornoob](https://www.ruby-forum.com/u/rornoob)\
**Post date:** [April 26, 2008, 1:56am UTC](https://www.ruby-forum.com/t/cant-understand-why-this-works/135905/1 "2008-04-26T01:56:25Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![rornoob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/7bcc69/32.png) [@rornoob](https://www.ruby-forum.com/u/rornoob)\
**Post date:** [April 26, 2008, 2:04am UTC](https://www.ruby-forum.com/t/cant-understand-why-this-works/135905/2 "2008-04-26T02:04:08Z")

</div>

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](http://www.rubypal.com) for details and updates!

---

<div class="post-metadata">

**Author:** ![rornoob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/7bcc69/32.png) [@rornoob](https://www.ruby-forum.com/u/rornoob)\
**Post date:** [April 26, 2008, 2:31am UTC](https://www.ruby-forum.com/t/cant-understand-why-this-works/135905/3 "2008-04-26T02:31:04Z")

</div>

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