Written September 14, 2007. Tagged Ruby.
I often find
collection.include?(object) to read backwards. Consider
puts "Nice doggie!" if [:pug, :bulldog].include?(dog)
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:
collection = (args.length == 1 ? args.first : args)
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,
For better readability still, try something like
alias_method :one_of?, :in?
puts "Nice doggie!" if dog.one_of?(:pug, :bulldog)