you.not_nil? { |you| read.this }

written by admin on décembre 7th, 2006 @ 12:03

A thing that really annoys me is to check for nil values. For example having to do, in an ERB template

my template

<% unless a.super['long'].variable['accessor'].nil? %>
<%= do_something_with a.super['long'].variable['accessor'] %>
<%= do_something_else_with a.super['long'].variable['accessor'] %>
<% end %>

You'll say that I could use a local variable:

my template

<% the_var = a.super['long'].variable['accessor'] %> <% unless the_var.nil? %>
<%= do_something_with the_var %>
<%= do_something_else_with the_var %>
<% end %>

But I prefer to have a more "Ruby" way for that:

my template

<% a.super['long'].variable['accessor'].not_nil? do |the_var| %>
<%= do_something_with the_var %>
<%= do_something_else_with the_var %>
<% end %>

It is mutch nicer. Even more for one liners:

<%= do_something_with some_really_long_var unless some_really_long_var.nil? %>

becomes

<%= some_really_long_var.not_nil? { |v| do_something_with v } %>

Here is the code for the "not_nil?" method:

1
2
3
4
5
class Object
  def not_nil?
     yield self unless self.nil?
  end
end

Comments

  • Aníbal Rojas on 13 jan 21:12

    Why not, simplify it to: if a.super['long'].variable['accessor'] you don't really need the verbose nil? method (that's is going to be slowertoo)
  • Chris on 14 mar 23:53

    Simple, elegant and very much idiomatic ... nice stuff!

Post a comment

Options:

Size

Colors