I will summarize the iterative processing of Ruby.
The most used iterative method in Ruby. Convenient for arrays and hashes.
each.rb
fruits = ["apple", "banana", "grape"]
fruits.each{ |fruit| puts fruit }
The elements of the array fruits are taken out one by one from the youngest index, put in the argument fruit, and the processing in {} is executed. I'm using {} because it only processes 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, using do end makes it easier to write.
Convenient for processes that have a fixed number of repetitions.
times.rb
sum = 0
10.times { |n| sum += n }
sum #=> 45
Useful when the start and end numbers are fixed.
upto.rb
15.upto(20) do |age|
if age < 18
puts "#{age}No right to vote at age"
else
puts "#{age}I am over 18 years old, so I have the right to vote"
end
end
upto repeats the process in the direction of increasing the numerical value. Executes processing from the specified first number 15 to the last number 20.
downto.rb
20.downto(15) do |age|
if age < 18
puts "#{age}No right to vote at age"
else
puts "#{age}I am over 18 years old, so I have the right to vote"
end
end
downto repeats the process in the direction of decreasing the numerical value. Executes processing from the specified first number 20 to the last number 15.
Useful when the end 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, the process during while end is repeated. In the above code, the process ends when the total value sum exceeds 1000.
The until statement is the opposite of the while statement and repeats the process 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.
You can create an infinite loop with while true, but you can create it more simply 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
It is convenient to use the method / syntax used for iterative processing that suits the case.
An introduction to Ruby for those who want to become professionals Junichi Ito [Author]
Recommended Posts