views:

1441

answers:

6

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. Any help would be much appreciated.

+1  A: 
if (i >= 1 && i <= 10)
   do thing 1
...

This is just basic syntax in most languages, there may be another "Ruby" way of doing it that I am not aware of.

CookieOfFortune
This works, but the built-in === operator would be more appropriate.
Baldu
`i >= i` will always be true, by the way.
The Wicked Flea
+5  A: 

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

if (1..10) === i
Baldu
.include? works, but the === (1..10) does not.
CookieOfFortune
Oops. === is an operator on Range, not Integer. Fixed the answer, thanks.
Baldu
+2  A: 

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
Tim Hoolihan
I think this should have been the marked answer.
Geo
+12  A: 

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...
Vincent Robert
A: 

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.

m104
A: 
if i.between?(1, 10)
  do thing 1 
elsif i.between?(11,20)
  do thing 2 
...
rogerdpack