Loops and Repetitions in Ruby

1) times:

[integer].times do |i| ... end

e.g:

5.times do |i|
  puts "iteration: #{i}"
end

2) upto:

[start_val].upto [end_val] do |i| ... end

e.g:

1.upto 5 do |i|
  puts "iteration: #{i}"
end

3) downto:
it’s inverse of upto.

[end_val].downto [start_val] do |i| ... end

e.g:

5.downto 1 do |i|
  puts "iteration: #{i}"
end

4) step:

We can do both upto and downto with step loop. It’s very flexible.

a) [start_val].step [end_val] do |i| ... end
e.g:
1.step 5 do |i|
  puts "Iteration: #{i}"
end

for stepping:

b) [start_val].step [end_val], [incremental_val] do |i| ... end
e.g: 
1.step 5, 2 do |i|
  puts "Iteration: #{i}"
end

like downto:

c) [end_val].step [start_val], -1 do |i| ... end
e.g: 
5.step 1, -1 do |i|
  puts "Iteration: #{i}"
end

5) while
a)

while conditional [do]
  code
end

e.g:
i = 1
while i <= 5 do
  puts "Iteration: #{i}"
  i += 1
end

b)

code while condition

OR

begin 
  code 
end while conditional

e.g:
i = 1
begin
  puts "Iteration: #{i}"
  i +=1
end while i < 5

7) until
It’s similar to while but having reverse condition.

e.g:
i = 1
until i > 5 do
  puts "Iteration: #{i}"
  i += 1
end

8) for

for [var_name] in [rang] do ... end
e.g: 
for i in (1..10) do
  puts "Iteration: #{i}"
end

9) each

[rang].each do |[var]| ... end
e.g: 
(1..10).each do |i|
  puts "Iteration: #{i}"
end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s