Skip to content

Instantly share code, notes, and snippets.

@boffbowsh
Created January 23, 2012 22:21
Show Gist options
  • Select an option

  • Save boffbowsh/1665831 to your computer and use it in GitHub Desktop.

Select an option

Save boffbowsh/1665831 to your computer and use it in GitHub Desktop.
WTFRuby
1.9.3p0 :001 > case nil.class
1.9.3p0 :002?> when NilClass
1.9.3p0 :003?> p 'yay'
1.9.3p0 :004?> else
1.9.3p0 :005 > p 'wtf'
1.9.3p0 :006?> end
"wtf"
=> "wtf"
1.9.3p0 :007 > nil.class
=> NilClass
1.9.3p0 :008 > nil.class == NilClass
=> true
1.9.3p0 :009 > 'WTF?!!'
=> "WTF?!!"
@timblair

Copy link
Copy Markdown

Ruby case statements use === to make comparisons, which is aliased to is_a? at a class level. So what you're asking is "is NilClass an instance of NilClass?" hence the false return value.

>> case nil
>>   when NilClass
>>     "yay"
>>   else
?>     "wtf"
>>   end
=> "yay"

@boffbowsh

Copy link
Copy Markdown
Author

Very true, this stemmed from a couple of hours yakshaving working on a custom xml serializer for a godawful protocol. using case obj and then when Array wouldn't ever catch the array (because it was actually an AR::CollectionProxy, thanks Rails! But then AR::Relation or AR::CollectionProxy didn't work either). I had to switch to case; when obj.is_a?(Array) and it magically worked. This was just (what I thought was) an additional wtf I found along the way. Ta for the clarification :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment