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 1 year has passed since last update.

Ruby timesメソッドを使った繰り返し処理を行うプログラムを書く

Posted at

繰り返し処理を行うプログラムの作成

  • ユーザーに数字を入力してもらい、その数の回数だけHello world!と表示させるコードを記述します。
def output(num)
  num.times do
    puts "Hello world!"
  end
end

puts "何回表示させますか?"
num = gets.to_i
output(num)

解説

  • メソッド外の部分
puts "何回表示させますか?"
num = gets.to_i
output(num)

上記コードは、ファイルを実行したときにターミナルで出力される内容を書いています。
ユーザーに数字を入力させることで、「Hello world!」が何回表示されるのかを実行するためです。
getsメソッドで入力した値は、全て文字列で返します。
そのため、.to_iを付けて数値に変換させます。

  • output(num)
    ユーザーが入力した数値を、メソッド内で呼び出したいため、numという引数を使います。

  • outputメソッド内
    繰り返し表示させるためには、timesメソッドを使います。
    ユーザーがターミナルで入力した数値が変数numに代入され、処理が行われるということです。

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?