案例陈述和与整数的比较

时间:2016-11-30 22:12:34

标签: ruby case

我是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

有原因吗?如果有人可以帮助我,我会非常感激

1 个答案:

答案 0 :(得分:11)

试试这个。

 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 [参数]是范围的元素,则返回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