It's an embarrassing story, but until recently, when I was told to "write beautiful code", I was conditioned reflexively thinking "I shouldn't have an error." However, as I understood the term refactoring and touched on some notations and methods, I began to think that beautiful code was beautiful (a little exaggeration: sweat_smile :), so I will give you an example of basic refactoring. I would like to introduce you.
Output the sum of consecutive arrays from 1 to 5. (The answer is 15) I would like to challenge how to describe this neatly and derive it.
p 1 + 2 + 3 + 4 + 5
… A program or a calculator? The simplest description of the level. Of course, it is not possible to deal with the case of calculating the total of numbers from 1 to 100. I want to make it expandable.
numbers = [1,2,3,4,5]
sum = 0 #Assign 0 to the variable sum
numbers.each do |n|
sum += n #Repeatedly add the block variable n to the variable sum
end
p sum
It may be the first code you learn in each statement. Even in programming, I get the feeling that "it is troublesome to write the elements of an array as 1,2,3 ..." and "I want to make each statement compact over several lines".
numbers = (1..5) #Creating a range object. 1~Means an array of consecutive values up to 5.
sum = 0
numbers.each {|n| sum += n } #{}Put it on one line using the block notation of.
p sum
__ (first value .. last value) __ can represent a range of values.
numbers = (1..5)
p sum = numbers.inject(0) {|n, s| n + s}
#The inject method works according to the following flow.
#The first argument of the method goes into the first argument of the block.
#Each element of the array is entered in order in the second argument of the block.
#The return value of the block is inherited by the first argument of the block.
#When the iterative process is completed, the return value of the block becomes the return value of the inject method.
By using the inject method, we were able to handle multiple arguments and fit them in two lines.
In the future, I will continue to read the "Readable Code" that I heard as a good book, and I will do my best to write a beautiful code that will show my heart. If you have an opinion that "it's more concise to write like this", please let us know!
Recommended Posts