1

I commonly use the [1, 2, 3].include? foo idiom. There is nothing inherently wrong with this, but for readability's sake, it would be nice to be able to write foo.is_in? [1, 2, 3]. Does the core or standard library have a method that will do this?

wersimmon
  • 2,779
  • 3
  • 21
  • 35

2 Answers2

1

No there is no such method in the standard. Implement it on your own:

class Object
  def is_in? a
    return a.include?(self)
  end
end

Note in the above code I never check the type of a so you will get an error if include? is not defined for a.

Ivaylo Strandjev
  • 66,530
  • 15
  • 117
  • 170
0

Not exactly in the same way as you want, but you can rewrite this

if [1, 2, 3].include? foo
  do_this
else
  do_that
end

to this:

case foo; when 1, 2, 3
  do_this
else
  do_that
end
sawa
  • 160,959
  • 41
  • 265
  • 366