In your example, you can simply replace null
with `nil and it will work fine.
require 'erb'
template = <<EOS
<% if (@objectname != nil) then %>
@objectname is not nil
<% else %>
@objectname is nil
<% end %>
EOS
@objectname = nil
ERB.new(template, nil, '>').result # => " @objectname is nil\n"
@objectname = 'some name'
ERB.new(template, nil, '>').result # => " @objectname is not nil\n"
Contrary to what the other poster said, you can see above that then
works fine in Ruby. It's not common, but it is fine.
#blank?
and #present?
have other implications. Specifically, if the object responds to #empty?
, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.
Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be
require 'erb'
template = <<EOS
<% if @objectname %>
@objectname is not nil
<% else %>
@objectname is nil
<% end %>
EOS
@objectname = nil
ERB.new(template, nil, '>').result # => " @objectname is nil\n"
@objectname = 'some name'
ERB.new(template, nil, '>').result # => " @objectname is not nil\n"
If you explicitly need to check nil
and not false
, you can use the #nil?
method, for which nil is the only object that will cause this to return true.
nil.nil? # => true
false.nil? # => false
Object.new.nil? # => false