我是Ruby的新手,我不知道为什么在这种情况下它的行为如此:

def evaluate(number)
  case
  when number<0
    puts "#{number} is negative"
  when 0..50
    puts "#{number} is between 0 and 51"
  when 51..100
    puts "#{number} is between 51 and 100"
  else
    puts "#{number} is greater than 100"

  number = gets.chomp.to_i

  puts evaluate(number)

例如,当通过-4时,它可以工作,但是如果我在情况下加上数字
  def evaluate(number)
  case number
  when number<0 ...

然后它将负值解释为好像是else,并打印出大于100的值

有什么理由吗?如果有人可以帮助我,我将非常感激

最佳答案

试试这个。

 def evaluate(number)
   case number
   when -Float::INFINITY...0
     puts "#{number} is negative"
   when 0..50
     puts "#{number} is between 0 and 51"
   when 51..100
     puts "#{number} is between 51 and 100"
   else
     puts "#{number} is greater than 100"
   end
 end

puts evaluate(-43)
 # -43 is negative
puts evaluate(0)
 # 0 is between 0 and 51
puts evaluate(27)
 # 27 is between 0 and 51
puts evaluate(100)
 # 100 is between 51 and 100
puts evaluate(9999)
 # 9999 is greater than 100

另外,由于case语句使用===进行比较,因此您可以编写
 def evaluate(number)
   case
   when number < 0
     puts "#{number} is negative"
   when (0..50) === number
     puts "#{number} is between 0 and 51"
   when (51..100) === number
     puts "#{number} is between 51 and 100"
   else
     puts "#{number} is greater than 100"
   end
 end

这实际上就是上述第一个案例陈述中发生的事情。

请参见Range#===:“如果obj [argument]是范围的元素,则返回true,否则返回false。”换句话说,且仅当(1..10) === number时,true才是(1..10).include?(number)

我不是在提倡这种选择。我介绍它是为了帮助说明案例陈述中的情况。以下是一个替代方法,它可能会更短一些,或者可能会更好地阅读。
 def evaluate(number)
   suffix =
   case number
   when -Float::INFINITY...0 then "negative"
   when 0..50                then "between 0 and 51"
   when 51..100              then "between 51 and 100"
   else                            "greater than 100"
   end
   puts "#{number} is #{suffix}"
 end

关于ruby - 案例陈述和整数比较,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40899186/

10-13 04:43