The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
The nil test

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Daniel Berger

Posts: 1383
Nickname: djberg96
Registered: Sep, 2004

Daniel Berger is a Ruby Programmer who also dabbles in C and Perl
The nil test Posted: Apr 11, 2005 4:22 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Daniel Berger.
Original Post: The nil test
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Daniel Berger
Latest Posts From Testing 1,2,3...

Advertisement
A post on ruby-talk today reminded me of something regarding nil and method chaining today. You sometimes see folks writing something like this:
if foo.nil? || foo.empty?

This happens because they quickly realize that if 'foo' is nil, then trying to call foo.empty? will fail because there's no such method .empty? for nil. However, that line can be reduced as follows:
if foo.to_s.empty?

This works because calling .to_s on nil returns "" (an empty
String). Also note that calling .to_i on nil returns 0, which can come in handy.

Technically, my version is a bit slower. The former could, in theory be faster, since my version always calls .to_s. That overhead is extremely minimal (not that I have any benchmarks handy).

The real point I wanted to get to is that you should always, always, ALWAYS have unit tests that test nil values for your method arguments, even if it's just to verify that an error is raised. This will quickly weed out the "NoMethodError: undefined method ..." errors (the equivalent of everyone's favorite Java error, NullPointerException).

Read: The nil test

Topic: A new job? Previous Topic   Next Topic Topic: Worst band ever

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use