puts 'guess my favorite num'
x = gets.chomp
unless x.kind_of?(Fixnum)
puts "it's not a Numeric symbol"
if x=="2"
puts "Well done!"
if x!=2 || x.is_a?(Fixnum)
puts "Try more, dude"
end
end
end
尝试学习ruby,但我的代码不起作用:-(需要3个不同条件的var。哪里有bug?
答案 0 :(得分:2)
考虑一下:
#!/usr/bin/env ruby
puts "Guess my favorite num."
x = gets.chomp
begin
if Integer(x) == 2
puts "Well done!"
else
puts "Try more, dude."
end
rescue ArgumentError
puts "It's not an integer."
end
答案 1 :(得分:1)
半人为的例子,但你可能正在寻找elsif
:
puts 'enter a favorite num'
x = gets.chomp.to_i
if x == 2
puts "you entered 2"
elsif x !=2
puts "you did not enter 2"
end
另外 - 正如@Jan Dvorak指出的那样 - gets
方法返回一个字符串,你想要转换它(在这种情况下为整数)。
另一个解决方案是使用case
语句:
print 'enter a favorite num'
x = gets.chomp.to_i
case x
when 2
puts "you entered 2"
else
puts "you did not enter 2"
end
答案 2 :(得分:0)
你可能意味着类似的东西:
loop do
puts 'guess my favorite num'
x = gets.chomp
case x
when /\D/
puts "it's not a Numeric symbol"
when "2"
puts "Well done!"
break
else
puts "Try more, dude"
end
end