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