Created
February 19, 2014 05:55
-
-
Save boddhisattva/9086747 to your computer and use it in GitHub Desktop.
Loops in Ruby
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
# loops in Ruby | |
# While | |
x = 10 | |
while x >= 0 do | |
puts x | |
x = x - 1 | |
end | |
#-------------------------------------------------------------------------------------------------------------------------------- | |
puts("\n") | |
# Until | |
x = 0 | |
until x > 10 do | |
puts x | |
x = x + 1 | |
end | |
#-------------------------------------------------------------------------------------------------------------------------------- | |
puts("\n") | |
# While as a modifier | |
x = 5 | |
puts x = x + 1 while x < 10 | |
#-------------------------------------------------------------------------------------------------------------------------------- | |
puts("\n") | |
# Until as a modifier | |
a = [1,2,3] | |
puts a.pop until a.empty? # behaves like a stack.. the op is in LIFO manner | |
#-------------------------------------------------------------------------------------------------------------------------------- | |
#for loop implementation.. | |
puts("\n") | |
array = [ 1, 2, 3, 4, 5 ] | |
for element in array # note the use of built in keywords like element simplifies our usage.. | |
puts element # making ruby more simpler to use | |
end | |
puts("\n") | |
hash = { :a => 1, :b => 2, :c => 3 } # here key and value are built in keywords wrt hashes in Ruby.. | |
for key,value in hash | |
puts "#{key} => #{value}" | |
end | |
#-------------------------------------------------------------------------------------------------------------------------------- |
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
10 | |
9 | |
8 | |
7 | |
6 | |
5 | |
4 | |
3 | |
2 | |
1 | |
0 | |
0 | |
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
6 | |
7 | |
8 | |
9 | |
10 | |
3 | |
2 | |
1 | |
1 | |
2 | |
3 | |
4 | |
5 | |
a => 1 | |
b => 2 | |
c => 3 |
Author
boddhisattva
commented
Mar 2, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment