header

Ruby Control Structure

Ruby’s most basic control structure: if statement

if @writable
  @author = "josdem"
end

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"
end

An more idiomatic way would be:

unless @read_only
  @author = "josdem"
end

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
end

it’s:

until parking_lot.is_full?
  park +=1
end

Using modifier forms

Let’s return to this snippet code:

unless @read_only
  @author = "josdem"
end

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
end

Case Statement

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

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

With your donation, you help me to maintain this site and posts.





comments powered by Disqus