[Ruby] Ruby about various iterations

2 minute read

Introduction

Summarize about iterative processing of Ruby.

each method (array/hash)

The most used iterative method in Ruby. Useful for arrays and hashes.

each.rb


fruits = ["apple", "banana", "grape"]
fruits.each{ |fruit| puts fruit}

The elements of array fruits are taken out one by one from the ascending order of index, put in the argument fruit, and the processing in {} is executed. I use {} because the process is only one line,

each_do.rb


numbers = [1, 2, 3, 4, 5]
sum = 0
numbers.each do |number|
  if number %2 == 0
    sum += number / 2
  else
    sum += number
  end
end
sum #=> 12

For multiple lines, do end is easier to write.

times method (number of times to repeat)

Convenient for processing that has a fixed number of repetitions.

times.rb


sum = 0
10.times {|n| sum += n}
sum #=> 45

upto/downto methods (number)

Useful when the start and end numbers are fixed.

upto.rb


15.upto(20) do |age|
  if age <18
    puts "There is no right to vote at the age of #{age}"
  else
    puts "I have the right to vote because #{age} is over 18 years old."
  end
end

upto repeats the process to increase the numerical value. Performs processing from the specified first number 15 to the specified last number 20.

downto.rb


20.downto(15) do |age|
  if age <18
    puts "There is no right to vote at the age of #{age}"
  else
    puts "I have the right to vote because #{age} is over 18 years old."
  end
end

downto repeats the process to decrease the value. Performs processing from the specified first number 20 to the specified last number 15.

while statement/until statement (end condition)

Convenient when ending conditions are fixed

while.rb


array = (1..100).to_a
sum = 0
i = 0
while sum <1000
  sum += array[i]
  i += 1
end
sum #=> 1035

While the condition next to while is true, repeat the process during the while end. In the code above, the process ends when the sum sum exceeds 1000.

The until statement is the opposite of the while statement, and because the process is repeated when the condition is false,

until.rb


array = (1..100).to_a
sum = 0
i = 0
until sum >= 1000
  sum += array[i]
  i += 1
end
sum #=> 1035

The above code has the same meaning as while.rb.

loop method (infinite loop)

An infinite loop can be created even while while true, but it can be made simpler by using the loop method.

loop.rb


numbers = [1, 2, 3, 4, 5, 6, 7]
loop do
  n = numbers.sample
  puts n
  break if n == 7
end

Summary

It is convenient to use the method/syntax that is used for the iterative process, according to the case.

References

Introduction to Ruby for professionals Junichi Ito [Author]

Tags:

Updated: