Determining if a variable is within range?

人盡茶涼 提交于 2019-11-29 19:03:57
if i.between?(1, 10)
  do thing 1 
elsif i.between?(11,20)
  do thing 2 
...

Use the === operator (or its synonym include?)

if (1..10) === i

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...

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

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

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?

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

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

true

A more dynamic answer, which can be built in Ruby:

def select_f_from(collection, point) 
  collection.each do |cutoff, f|
    if point <= cutoff
      return f
    end
  end
  return nil
end

def foo(x)
  collection = [ [ 0, nil ],
                 [ 10, lambda { puts "doing thing 1"} ],
                 [ 20, lambda { puts "doing thing 2"} ],
                 [ 30, lambda { puts "doing thing 3"} ],
                 [ 40, nil ] ]

  f = select_f_from(collection, x)
  f.call if f
end

So, in this case, the "ranges" are really just fenced in with nils in order to catch the boundary conditions.

For Strings:

(["GRACE", "WEEKLY", "DAILY5"]).include?("GRACE")

#=>true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!