[Ruby] [Ruby/Refactoring] From iterative processing of Ruby such as Java and C language to iterative processing like Ruby

1 minute read

Introduction

After studying Java and C languages, I have implemented programs in Ruby. At that time, the loop statement that was initially implemented has implementation contents like Java, Since it didn’t look like Ruby, I refactored it as follows.

I would appreciate it if you could write a Ruby-like description method than the one below.

Program content

Program to display odd numbers from 0 to 100

Before correction

Iterative processing is described according to the following grammar of Ruby. It is easy to write because I am used to the for statement in Java and C language.

for variable in object do
  Process to be executed repeatedly
end

loop.rb


for n in 0..100 do
  if n %2 != 0 then
    puts n
  end
end

Revised

As I study Ruby, I recognize that it is common to use each for iterative processing. In addition, a method that handles integers odd? even? By knowing the instance method like select like below You can modify the iteration process.

# Returns true if it is an odd number
3.odd? # execution result true

# select method
# Each element is judged by block and only true element is returned
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
puts array.select(&:odd?) # execution result 1 3 5 7 9

loop.rb


(0..100).select(&:odd?).each do |n|
  puts n
end

Finally

It seems that each method of Ruby for statement is executed at the time of execution. (It is said that the fact that another method is actually executed as described above is called syntax sugar.) When writing iterative processing in Ruby, each is personally recommended.

I would like to take the following lessons from this revision. ** If you enter Ruby, follow Ruby ** I want to work with the same spirit when learning other languages.