0
0

More than 3 years have passed since last update.

timesメソッドについての考察

Posted at

timesメソッドについて

 

timesメソッドのスポットの位置と、ブロック変数の意味は0から数える以外にあるのか正確な認識ができていないと感じ、何パターンか試して自分なりにまとめてみました。 


colors = ["あか", "あお", "きいろ"]
element_count = colors.length

i = 0
num = 0

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

# num = 0  ここでnumを定義=>変数が定義されていないのに+は何故のエラーが発生
       # → timesメソッド内をnum = 1にすると出力はでるが、0となる(スポット)

puts i #出力は0
puts num  #出力は3

#------------------------------------------------------------------
#ブロック変数iで定義されたiを出力しようするとNameError(変数名iは定義されていない)。
#ブロック変数は出力できない。
#ブロック変数iと変数iは同じ見た目だが、全く別の変数である。

認識の違いや、補足等あれば教えていただけると幸いです。

 

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0