After studying Java and C language, I implement the program in Ruby. At that time, the loop statement that was initially implemented has a Java-like implementation content, Since it didn't look like Ruby, we refactored it as follows.
I would appreciate it if you could teach me if there is a Ruby-like description method than the following.
A program that displays odd numbers from 0 to 100
Describe the iterative process according to the following Ruby grammar. Easy to write because you are used to for statements in Java and C.
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
As you study Ruby, you will recognize that it is common to use each for iterative processing. In addition, methods that handle integers odd? Even? By knowing the instance method like select, as below You can modify the iterative process.
#Returns true if it is odd
3.odd? #Execution result true
#select method
#Judge each element as a block and return only the true element
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
The Ruby for statement seems to have each method executed at runtime. (It seems that the fact that another method is actually executed as described above is called syntactic sugar.) When writing iterative processing in Ruby, I personally recommend each.
From this revision, I would like to learn the following lessons. *** Enter Ruby and follow Ruby *** I would like to work with the same spirit when learning other languages.
Recommended Posts