我如何使用elsif和范围?

时间:2014-05-27 15:09:37

标签: ruby

我有以下代码:

var_comparison = 5
print "Please enter a number: "
my_num = Integer(gets.chomp)
if my_num > var_comparison
    print "You picked a number greater than 5!"
elsif my_num < var_comparison
    print "You picked a number less than 5!"
elsif my_num > 99
    print "Your number is too large, man."
else
    print "You picked the number 5!"
end

口译员无法区分接受规则>5>99。我怎么做到6-99之间的任何数字返回&#34;你选择了一个大于5的数字!&#34;,但是100或更高的数字返回&#34;你的数字太大了,伙计! &#34;

我是否需要以某种方式具体陈述范围?我最好怎么做?是否采用正常范围的方法,例如

if my_num 6..99

if my_num.between(6..99)

4 个答案:

答案 0 :(得分:3)

您可以将其表达为范围,但重新排列条件的顺序以实现您想要的更简单。解释器按照写入顺序运行条件if / else语句,在条件为真或达到else时停止。这使得订单很重要。我们可以知道,如果我到达elsif,则所有前述条件都必须为假。所以在你的代码中:

var_comparison = 5
print "Please enter a number: "
my_num = Integer(gets.chomp)
if my_num > 99
    # my_num is > 99
    print "Your number is too large, man."
elsif my_num > var_comparison # to get here, my_num must be <= 99
    print "You picked a number greater than 5!"
elsif my_num < var_comparison
    print "You picked a number less than 5!"
else
    print "You picked the number 5!"
end

如果您需要将数字表示为范围(如果您的条件逻辑变得更复杂),您可以执行以下操作:

if (6..99).cover?(my_num)

答案 1 :(得分:2)

  

显然,口译员无法区分接受规则&gt; 5或&gt; 99.

是的确如此:它以文字顺序测试条件!由于100大于5且大于99,因此两个条件都匹配,但在if / elseif链中,只评估一个条件。你应该移动条款来实现你想要的目标。

答案 2 :(得分:0)

使用elseif / case

,而不是使用when
def test_range(foo)
  case foo
  when 5 .. 99
    puts "#{ foo } is in range"
  else
    puts "#{ foo } is out of range"
  end
end

test_range(4)
test_range(5)
test_range(99)
test_range(100)
# >> 4 is out of range
# >> 5 is in range
# >> 99 is in range
# >> 100 is out of range

在你的代码中,它需要有点不同,因为小于和大于的测试不适合正常范围测试,因为它们期望离散的最小值和最大值。所以,相反,这就是我要做的事情:

my_num = 5
case 
when my_num > 99
  puts "Your number is too large, man."
when my_num > 5
  puts "You picked a number greater than 5!"
when my_num < 5
  puts "You picked a number less than 5!"
else
  puts "You picked the number 5!"
end

我发现if / elseif / else的长链变得难以阅读,所以我更喜欢case语句。

答案 3 :(得分:0)

正如Kilian所说,如果条款按顺序进行评估,那么第一个匹配将被视为所选条款。

您甚至可以使用case; when来实现此目标:

Infinity = 1.0/0

var_comparison = 5
print "Please enter a number: "
my_num = Integer(gets.chomp)
case my_num
  when -Infinity...var_comparison
    puts "You picked a number less than #{var_comparison}!"
  when var_comparison
    puts "You picked the number #{var_comparison}!"
  when var_comparison..99
    puts "You picked a number greater than #{var_comparison}!"
  else
    puts "Your number is too large, man."
end