Control Structures

Conditional structures

Loops

#  Repeats a block of code until the test expression is evaluated to false

>> i = 0 
?> while i < 5 do
?>   print i = i + 1,"\s"
>> end
1 2 3 4 5
=> nil

>> i = 0
>> print i = i + 1,"\s"  while i < 5
1 2 3 4 5

Iterators & Enumerators

>> (1..5).each {|i| print "#{i}\s" }
1 2 3 4 5 => 1..5

# Blocks!
?> ('a'..'h').each do |c|
?>   print "#{c}\n"
>> end
a
b
c
d
e
f
g
h
=> "a".."h"
>> array = [1, 2, 3, 4, 5]
>> array.map { |x| x**2 }
=> [1, 4, 9, 16, 25]
>> array.map! { |x| x**2 }
=> [1, 4, 9, 16, 25]
>> array
=> [1, 4, 9, 16, 25]

Enumerator: object whose purpose is to enumerate another enumerable object. This means that enumerators are enumerable too.

If you have a method that uses an enumerable object, you may not want to pass the enumerable collection object because it is mutable and the method may modify it.

So you can pass an enumerator created with to_enum and nothing will happen to the original enumerable collection

>> a = [1,2,3,4]
>> a.each 
=> #<Enumerator: ...>
>> a.map 
=> #<Enumerator: ...>
>> a.select 
=> #<Enumerator: ...>

Altering structured control flow (break/next)

>> for i in 1..10
 |    print i,"\s"
 |    break if i == 5
 | end
=> 1 2 3 4 5 => nil

>> (1..10).each do |i|
 |    print i,"\s"
 |    break if i == 5
 | end
=> 1 2 3 4 5 => nil

BEGIN/END

These are two reserved words in Ruby.

# BEGIN allows the execution of Ruby code at the beginning of a Ruby program
# END allow sthe execution if Ruby code at the end of a Ruby program

BEGIN {
  puts "Beginning"
}

END {
  puts "Ending"
}

puts "Normal control flow"

=>
Beginning
Normal control flow
Ending

Last updated