作成したコードは2回しか繰り返されません。 "continue_question"メソッドの2回目の "y"を入力すると、コードは停止します。Ruby初心者:コードは2回繰り返します
def greeting
puts "Hello! Please type your name: "
name = gets.chomp.capitalize
puts "It is nice to meet you #{name}. I am a simple calculator application."
puts "I can add, subtract, multiply, and divide."
end
greeting
def calculator
puts "First number: "
@n1 = gets.chomp.to_i
puts "Secons number: "
@n2 = gets.chomp.to_i
def calculation
puts "Type 1 to add, 2 to subtract, 3 to multiply, or 4 to divide two numbers: "
operation_selection = gets.chomp.to_i
if operation_selection == 1
@result = @n1 + @n2
elsif operation_selection == 2
@result = @n1 - @n2
elsif operation_selection == 3
@result = @n1 * @n2
elsif operation_selection == 4
@result = @n1/@n2
else
puts "Something went wrong!"
calculation
end
end
calculation
puts "Your Result is #{@result}"
end
calculator
def continue_question
puts "Do you want to continue? (y/n)"
continue = gets.chomp.to_s
if continue == "y"
calculator
elsif continue == "n"
puts "Bye!"
else
puts "What?"
continue_question
end
end
continue_question
このように再帰的にメソッドを呼び出すのではなく、 'while'または' loop'を使うことも考えられます。しかし、それはおそらく元の質問の範囲を超えているより大きなリファクタです。 –