我不明白为什么我的If else语句不能正常工作,如果我输入'y'那么它会评估if else语句的最后一部分。
puts('give 1: ')
nr1= Integer(gets)
puts('give 2: ')
nr2= Integer(gets)
selection = gets.to_s
if (selection == "y".upcase)
puts "Result is #{nr1+nr2}"
elsif (selection =="v".upcase)
puts "Result is #{nr1-nr2}"
else (selection == "k".upcase)
puts "Result is #{nr1*nr2}"
end
答案 0 :(得分:4)
进入的一个好习惯是将其分解为正确的case
声明:
case (selection.upcase)
when 'Y'
puts "Result is #{nr1+nr2}"
when 'V'
puts "Result is #{nr1-nr2}"
when 'K'
puts "Result is #{nr1*nr2}"
else
puts "I don't know what you mean."
end
现在重要的是要注意selection == "y".upcase
将selection
与"Y"
进行比较,它不会取消您的选择。我已经通过使用selection
作为case
正在操作的东西来调整{{1}}上的不区分大小写的匹配。
答案 1 :(得分:1)
您缺少#chomp
方法。由于\n
附加到STDIN,您可以使用#chomp
删除。
2.2.2 :032 > selection = gets
y
=> "y\n"
2.2.2 :033 > selection.chomp
=> "y"
您可以按如下方式更新代码:
selection = gets.to_s.chomp.upcase
if selection == 'Y'
puts "Result is #{nr1+nr2}"
elsif selection == 'V'
puts "Result is #{nr1-nr2}"
elsif selection == 'K'
puts "Result is #{nr1*nr2}"
else
puts 'Invalid input'
end
虽然,ruby case
在这里最适合。类似的东西:
case selection.upcase
when 'Y'
puts "Result is #{nr1 + nr2}"
when 'V'
puts "Result is #{nr1 - nr2}"
when 'K'
puts "Result is #{nr1 * nr2}"
else
puts "Invalid input. Please provide a valid input [Y/V/K]"
end
答案 2 :(得分:0)
一种选择是使用哈希。
h = { 'Y'=>:+, 'V'=>:-, 'K'=>:* }
selection = gets.chomp.upcase
puts "Result is #{nr1.public_send(h[selection], nr2)}" if h.key?(selection)