Wednesday, September 5, 2007

Sick of undefined method * for nil:NilClass

Cool ruby trick to simply your code: if ['href'] == nil then use ""
So undefined method * for nil:NilClass basically means that the method your calling doesn't exist on the Nil class i.e. a NullReferenceException.

a = nil
a.size
=> undefined method * for nil:NilClass

but if you want to assume a default you can use the || operator to fake out ruby

(nil || "") => ""

a = nil
(a || "").size
=> 0


(!a['href'] || "").index('javascript:')

Sweet huh! :-)

2 comments:

rajat said...

hmm, would be helpful if you gave some context. otherwise i have no idea how to fix this error.

Justin Beck said...

I added some explanation that should help.