Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
May 9 ’10

Convert anything to boolean

Just add !! (a.k.a. the double bang operator) before any statement:

>> @document = Document.new
=> <Document id: nil, title: nil>

>> @document.title
=> nil
>> !!@document.title
=> false

>> @document.title = "My new document"
>> !!@document.title
=> true

In Rails, you can use the name of your attribute followed by a question mark:

>> @document.title?
=> true

>> @document.title = nil
>> @document.title?
=> false

If you want to read more about this, I recommend the following blogposts and their comments:

This tip was submitted by Vladimir Rybas.

18 notes 0 comments

  1. meetdom reblogged this from rubyquicktips
  2. sanemat reblogged this from rubyquicktips
  3. vrybas submitted this to rubyquicktips

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus