Basic Ruby idioms for Ruby on Rails

January 21, 2008

 
No Gravatar

I was chatting with a few friends who as of late, have had an increasing interest in Rails. All of them want to learn RoR for different reasons, but although their reasons for learning are different they seem to have a set of common questions. I thought I’d put together a post with a few common idioms that have been irking them.

empty!
The “bang” method can be attached to the end of other methods. These methods often indicate something destructive…bang! @class.destroy!

empty?
The “predicate” methods will return a true or false. @class.empty?

a || b
This expression first evaluates a, if it isn’t false or nil or false then ruby stops evaluating the expression and returns a. If it is false or nil, it will return b. I use this to return a default value if the first value hasn’t been set (read: page title).

a ||= b
Assign a the value of b if a doesn’t already have a value. So, count ||= 0 will set count to 0, if count doesn’t already have a value.

count += 1
In PHP, we’d use i++ but in Ruby, we use this syntax.

blog comments powered by Disqus