Thursday, October 11, 2007

Ruby: Default Argument Gotcha

Tonight I got very frustrated chasing a bug.

I was getting a method missing for a nil object with the + method.

def text_area_field(val="", attrs={})
add_label(attrs) do
open_tag("textarea", attrs) +
val +
"</textarea>"
end
end

I thought that if val was nil it would be set to a blank string. This is only the case when it's nil because it wasn't specified. I was sending nil to it from another method, and so it really did put a nil in there. Nasty.

I changed it to this and it worked as expected.

def text_area_field(val, attrs={})
val ||=""
add_label(attrs) do
open_tag("textarea", attrs) +
val +
"</textarea>"
end
end

3 comments:

Anonymous said...

Thanks for sharing your experience; knowing this could save me some debugging time!

dennis said...

This is exactly what I was looking for. Thanks!

Anonymous said...

It is very interesting for me to read that blog. Thank you for it. I like such topics and everything connected to them. I definitely want to read a bit more soon.