![Screenshot 2020-08-31 15.49.56.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/694973/7de31e7d-4555-29a3-20ac -21aa281f02fc.png)
sum = 0
10.times do |i|
sum = sum + i + 1
end
sum = 0
numbers = [1,2,3,4,5,6,7,8,9,10]
numbers.each do |n|
sum += n
end
I use the times method in the model answer, whereas I use the each method to repeatedly calculate the array. The common point is that the value sum is defined outside the block, and the processing to be performed for that sum is described in the block from do to end. But writing everything from 1 to 10 isn't smart. There is a range object that represents a range of consecutive values such as "1 to 10". Create a range object using ... or .. like this:
1 ... 10 (including 10) 1..10 (not including 10) You can use the to_a method on this range object to create a contiguous array of values
![Screenshot 2020-08-31 16.24.21.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/694973/da10d3d6-3cdf-7c2b-17f5 -93c9b25ea192.png) You now have a continuous array of up to 10! You can also create an array in the same way by using * and a range object in []. This is called splat expansion. It will be as follows.
If you put together the above and make the answer of the example again, it will be as follows
sum = 0
numbers = [*1..10]
numbers.each do |n|
sum += n
end
I was able to make it much cleaner from the beginning! You can also make it even more compact by using the each method directly on the range object. At the same time, instead of using do ... end as the block notation, we will use {}.
sum = 0
(1..10).each{ |n| sum += n }
Introduced how to make iterative calculation compact by using range object and to_a method in each method. When it comes to programming, not only is the answer given, but it's not easy for the viewer to understand, and it's easier to write code there. I would like to continue to output with an awareness of how easy it is to write code!
Introduction to Ruby for professionals From language specifications to test-driven development / debugging techniques Software Design plus Kindle version Junichi Ito () https://www.amazon.co.jp/dp/B077Q8BXHC/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1
Recommended Posts