0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

繰り返し処理

Posted at

#1.以下のプログラム実行後に出力される最終的な値は何か。

8.times do |num|
  num = num + 1
  puts num
end

答えは8

解説
timesメソッドは数値の値によってその値の回数だけ処理を繰り返すメソッドである。
そして||で囲うということはブロック変数を定義している。ブロック変数の最初の値は0。0から数える。
繰り返し処理が一回実行されるごとにブロック変数には一ずつ加算した値が代入される。
今回は8回繰り返されるので最終的に値は8になる。

#2.以下のプログラム実行後に出力される値は何か

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

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

puts i

答えは エラーが起こる
解説
ブロック変数||は繰り返し処理の中でしか使えない。
今回はそのブロック変数を繰り返し処理の外で記述してしまっているためエラーが起こる。
puts iは中に入れればOK!

#3.以下のプログラム実行後に出力される値

posts = ["あか", "みどり", "黄色", "オレンジ", "黒"]

num = 0

posts.each do |post|
  num = num + 1
end 

puts num

答え5
解説
each文を使用すると配列の要素分だけ処理が繰り返される。
今回postsの中身は5個入ってるから5回処理を繰り返す。
処理内容は一回ごとにnum+1なので最終的にnumは5になる。

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?