[Ruby] Consideration on times method

less than 1 minute read

About <h1>times method

I felt that I couldn’t recognize exactly the position of the spot of the times method and the meaning of the block variable other than counting from 0, so I tried several patterns and tried to put together myself. ‥

colors = ["red", "blue", "yellow"]
element_count = colors.length

i = 0
num = 0

element_count.times do |i|
    i += 1
    num += 1

# num = 0 where num is defined => variable is undefined + causes error
       If you set num = 1 in the # → times method, the output will be output, but it will be 0 (spot)

puts i # output is 0
puts num # output is 3

#------------------------------------------------- -----------------
# Error when trying to output i defined by block variable i (variable name i is not defined).
# Block variables cannot be output.
# Block variable i and variable i look the same, but they are completely different variables.

We would appreciate it if you could tell us about any differences in perception or supplements.