Different ways of Iterating over an Array in Ruby (Just for me)

1) .each do |val| … end

2) .each_with_index do |val, index| … end

3) a) .map do … end  => returns new array

b) .map.with_index do |val, index| … end

4) .any? do |val| {condition} end   => returns true or false

5) .all? do |val| {condition} end   => returns true if all value satisfy the condition otherwise false

6) .select do |val| {condition} end   => returns an array of those values which satisfy condition.

7) .find do |val| {condition} end   => returns first value which passes condition.

8) .find_all do |val| {condition} end   => returns all those value which satisfy conditon. It’s equivalent to .select

9) .inject([initial_value_of_var1]) do |var1, var2 | … end => returns var1

 

Advertisements

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