Skip to content

Instantly share code, notes, and snippets.

@boddhisattva
Created February 19, 2014 05:55
Show Gist options
  • Save boddhisattva/9086747 to your computer and use it in GitHub Desktop.
Save boddhisattva/9086747 to your computer and use it in GitHub Desktop.
Loops in Ruby
# 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
#--------------------------------------------------------------------------------------------------------------------------------
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
@boddhisattva
Copy link
Author

[test](http://apidock.com/ruby/Symbol/to_i_) this out test this out

[test](http://apidock.com/ruby/Symbol/to_i_) this out

to_i returns an integer representation of an object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment