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条回答
forever°为你锁心
2楼-- · 2019-01-30 00:55

For Strings:

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

#=>true

查看更多
孤傲高冷的网名
3楼-- · 2019-01-30 00:56

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

if (1..10) === i
查看更多
forever°为你锁心
4楼-- · 2019-01-30 00:58

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.

查看更多
登录 后发表回答