nil.blank? => true
Dan Manges has written on the fact that in Ruby even nil is an object. His blog doesn’t seem to allow commenting, so I couldn’t, but I wanted to point something out for Rubyists on Rails. Rails modifies NilClass (of which nil is an instance) to respond true to the method blank?. String#blank? returns true if the string is empty, effectively aliasing String#empty?.
What this means is that Rails developers can do this:
do_something if @params[:some_field].blank?
instead of this:
do_something if @params[:some_field].nil? or @params[:some_field].empty?
In either example, if @params[:some_field] is either nil or an empty string, do_something will be called. But the first example is shorter, easier to write, and easier to understand.
Thank you for this tip
Thanks … that wasn’t clear to me!
I'm not sure this will work.
If params[:some_field] is nil, then:
>> nil.blank?
NoMethodError: undefined method `blank?' for nil:NilClass
I believe you would still need to preceed it with a "if params[:some_field].nil? or …"
Joe, are you using Rails? Rails adds the #blank? method. You can add it yourself easily enough if you’re not using Rails.
Note that if you’re using Rails but testing this in irb, it won’t work. You’d need to test it in script/console.
Jer:
You are correct; I had done irb instead of script/console !