object.in?(collection)

Written . Tagged Ruby.

I often find collection.include?(object) to read backwards. Consider

1
puts "Nice doggie!" if [:pug, :bulldog].include?(dog)

I think

1
puts "Nice doggie!" if dog.in?(:pug, :bulldog)

reads a lot better.

This may seem obvious to many. My intention is to promote the idea of doing things this way to those who hadn’t considered it, and the (rather straightforward) implementation as a convenience.

This is the code I use in a current Rails project:

1
2
3
4
5
6
class Object
  def in?(*args)
    collection = (args.length == 1 ? args.first : args)
    collection.include?(self)
  end
end

The conditionals make it so you can do either dog.in?([:pug, :bulldog]) (easier if the collection is in a variable/constant) or dog.in?(:pug, :bulldog) (easier if you enumerate the collection right there). If you just want the former syntax,

1
2
3
4
5
class Object
  def in?(collection)
    collection.include?(self)
  end
end

will do.

For better readability still, try something like

1
alias_method :one_of?, :in?

and then

1
puts "Nice doggie!" if dog.one_of?(:pug, :bulldog)