Ruby on Rails gotcha with empty? vs nil?

June 16th, 2008

Just got bitten by this one in Ruby on Rails.
If you use empty? to check a hash slice that doesn’t exist you get an error, instead of the behavior of nil? which simply  reports that it is actually nil …


irb(main):004:0> test = {}
=> {}
irb(main):005:0> test = {'test' => '1'}
=> {"test"=>"1"}
irb(main):006:0> test
=> {"test"=>"1"}

irb(main):007:0> test.empty?
=> false
irb(main):008:0> test[test]
=> nil
irb(main):009:0> test['test']
=> “1″
irb(main):010:0> test['test'].empty?
=> false
irb(main):011:0> test['test'].nil?
=> false
irb(main):012:0> test['testx'].nil?
=> true
irb(main):013:0> test['testx'].empty?
NoMethodError: undefined method `empty?’ for nil:NilClass
from (irb):13
irb(main):014:0>

Entry Filed under: ruby on rails

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

January 2009
S M T W T F S
« Dec    
 123
45678910
11121314151617
18192021222324
25262728293031

Shared Rails Hosting

Most Recent Posts

Categories