Ruby Control Structure

Ruby’s most basic control structure: if statement

if @writable
  @author = "josdem"

Consider, however, what would happen if we turned the logic around: If the document is read only, the natural tendency would be to simply throw in a ! or not:

if not @read_only
  @author = "josdem"

An more idiomatic way would be:

unless @read_only
  @author = "josdem"

The body of the statement is executed only if the condition is false.

In the same way we avoid negative conditions in while loops. Thus it is not:

while ! parking_lot.is_full?
  park += 1


until parking_lot.is_full?
  park +=1

Using modifier forms

Let’s return to this snippet code:

unless @read_only
  @author = "josdem"

We should collapse the whole thing into a single line like this:

@author = "josdem" unless @read_only

You can also do similar things with while

park +=1 while parking_lot.has_space?

Using Each

beers = ['IPA', 'Lagrimas Negras', 'Calavera']

beers.each do |beer|
  puts beer

Case Statement

framework = case language
when 'Groovy'
  puts 'Grails'
when 'Ruby'
  puts 'Rails'
  puts 'I Do Not Know'

This is equivalent and more compact:

framework = case language
  when 'Groovy' then 'Grails'
  when 'Ruby' then 'Rails'
  else 'I Do Not Know'

Another expression-based way to make decision is the ternary operator.

activity = programmer ? 'Java' : 'Futbol'

If the value of programmer is true, then the value of the whole expression is the thing between the question mark and colon, if the condition is false, the the expression evaluates the last part.

Return to the main article

comments powered by Disqus