The Pug Automatic

object.in?(collection)

Written September 14, 2007. Tagged Ruby.

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

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

I think

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:

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,

class Object
def in?(collection)
collection.include?(self)
end
end

will do.

For better readability still, try something like

alias_method :one_of?, :in?

and then

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