Ruby Control Structures

Ruby Control Structures

Conditional Statements

Conditionals are keywords that execute a certain statement under a specific condition.

  • If statement
  • Unless statement
  • Case statement

If syntax


if language == 'Ruby' [then]
  'awesome'
end
					

Several conditions case


if language == 'Ruby' && framework == 'Ruby on Rails' [then]
  'awesome'
end
					

Short syntax


'awesome' if language == 'Ruby'
					

If Else syntax


if language == 'Ruby' [then]
  'awesome'
else
  'not so good'
end
					

Short syntax (ternary operator)


language == 'Ruby' ? 'awesome' : 'not so good'
					

If Elsif syntax


if language == 'Ruby' [then]
  'awesome'
elsif language == 'Python' [then]
  'so so'
else
  'not so good'
end
					

Short syntax


if language == 'Ruby' then 'awesome'
elsif language == 'Python' then 'so so'
else 'not so good'
end
					

Unless


unless language == 'Ruby' [then]
  'not so good'
end
					

Short syntax


'not so good' unless language == 'Ruby'
					

Unless Else syntax


unless language == 'Ruby' [then]
  'not so good'
else
  'awesome'
end
					

Case


case language
when 'Ruby'
  'awesome'
when 'Python'
  'so so'
else
  'not so good'
end
					

case year
when 1800...1900 then 'XIX century'
when 1900...2000 then 'XX century'
when 2000...2100 then 'XXI century'
end
					

Loops & Iterators

Loops are blocks of program that are executed multiple times.

  • Loop
  • While
  • Until
  • For ... in
  • Upto
  • Times
  • Step
  • Each

Loop


loop do
  # block
 end
					

While


i = 0
while i < 10 do
  print i
  i += 1
end
					

Short syntax


i = 200
i -= 10 while i >= 100
					

Until


i = 0
until i >= 10 do
  print i
  i += 1
end
					

Short syntax


i = 200
i -= 10 until i < 100
					

For ... in


for i in 1..5
  print i, ' '
end
					

Break, next, redo statements

  • Break terminates the immediately enclosing loop.
  • Next skips to the end of the loop, effectively starting the next iteration.
  • Redo repeats the current iteration of the loop from the start.

i=0
loop do
  i += 1
  next if i < 3
  print i
  break if i > 4
end
					

Upto


0.upto(9) { |x| print x, ' ' } => "0 1 2 3 4 5 6 7 8 9 "
					

Downto


9.downto(0) { |x| print x, ' ' } => "9 8 7 6 5 4 3 2 1 0 "
					

Times


3.times { print 'Ho ' } => "Ho Ho Ho "
					

Step


0.step(12, 3) { |x| print x, ' ' } => "0 3 6 9 12 "
					

Each


[1, 2, 3, 5, 10].each { |n| print n, ' ' } => "1 2 3 5 10 "
					
Building a game

Code Style

Ruby Style Guide
Q&A
No questions? No answers!

Created by Vasyl Lasiak / @vlasiak