Created
March 16, 2012 21:00
-
-
Save mkoby/2052655 to your computer and use it in GitHub Desktop.
Intro to Ruby - 04 - Flow Control
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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