Determining if a variable is within range?

后端 未结 9 940
自闭症患者
自闭症患者 2020-12-12 12:02

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...
相关标签:
9条回答
  • 2020-12-12 12:44

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

    if (1..10) === i
    
    0 讨论(0)
  • 2020-12-12 12:46
    if i.between?(1, 10)
      do thing 1 
    elsif i.between?(11,20)
      do thing 2 
    ...
    
    0 讨论(0)
  • 2020-12-12 12:49

    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?

    0 讨论(0)
  • 2020-12-12 12:52

    For Strings:

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

    #=>true

    0 讨论(0)
  • 2020-12-12 12:53

    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
    
    0 讨论(0)
  • 2020-12-12 12:54

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

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

    true

    0 讨论(0)
提交回复
热议问题