Determining if a variable is within range?

2019-01-30 00:08发布

I need to write a loop that does something like:

if i (1..10)
  do thing 1
elsif i (11..20)
  do thing 2
elsif i (21..30)
  do thing 3
etc...

But so far have gone down the wrong paths in terms of syntax.

9条回答
一纸荒年 Trace。
2楼-- · 2019-01-30 00:33
if i.between?(1, 10)
  do thing 1 
elsif i.between?(11,20)
  do thing 2 
...
查看更多
老娘就宠你
3楼-- · 2019-01-30 00:33

As @Baldu said, use the === operator or use case/when which internally uses === :

case i
when 1..10
  # do thing 1
when 11..20
  # do thing 2
when 21..30
  # do thing 3
etc...
查看更多
淡お忘
4楼-- · 2019-01-30 00:40

Not a direct answer to the question, but if you want the opposite to "within":

(2..5).exclude?(7)

true

查看更多
\"骚年 ilove
5楼-- · 2019-01-30 00:41

You could use
if (1..10).cover? i then thing_1 elsif (11..20).cover? i then thing_2

and according to this benchmark in Fast Ruby is faster than include?

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-30 00:47

if you still wanted to use ranges...

def foo(x)
 if (1..10).include?(x)
   puts "1 to 10"
 elsif (11..20).include?(x)
   puts "11 to 20"
 end
end
查看更多
贼婆χ
7楼-- · 2019-01-30 00:49

You can usually get a lot better performance with something like:

if i >= 21
  # do thing 3
elsif i >= 11
  # do thing 2
elsif i >= 1
  # do thing 1
查看更多
登录 后发表回答