Skip to content

Instantly share code, notes, and snippets.

@mkoby
Created March 16, 2012 21:00
Show Gist options
  • Select an option

  • Save mkoby/2052655 to your computer and use it in GitHub Desktop.

Select an option

Save mkoby/2052655 to your computer and use it in GitHub Desktop.
Intro to Ruby - 04 - Flow Control
names = ["Michael", "John", "Paul", "George"]
names.each do |name|
puts "Hi, my name is #{name}"
end
# Result:
# Hi, my name is Michael
# Hi, my name is John
# Hi, my name is Paul
# Hi, my name is George
x = 2
# Basic IF statement
if( (x % 2) == 0) then puts "#{x} is divisible by 2" end
# Result: 2 is divisible by 2
# With failure
x = 5
if( (x % 2) == 0) then puts "#{x} is divisible by 2" end
# Result:
# The result is nothing, because 5 is not divisible by 2
# ELSE
if( (x % 2) == 0) then puts "#{x} is divisible by 2" else puts "#{x} is NOT divisible by 2" end
# Result: 5 is NOT divisible by 2
# Multiple lines
if( (x % 2) == 0)
puts "#{x} is divisible by 2"
else
puts "#{x} is NOT divisible by 2"
end
# Result: 5 is NOT divisible by 2
# Result is the same because we didn't change any code,
# we just spread it across multiple lines,
# making it easier to read
x = 10
while( x > 0 ) do
puts x
x -= 1
end
# Result:
# 10
# 9
# 8
# 7
# 6
# 5
# 4
# 3
# 2
# 1
# => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment