This seems like a ridiculous simple question to ask, but what is the shortest / most idiomatic way to rewrite this in Ruby?
if variable == :a or variable == :b or variable == :c or variable == :d # etc.
I saw this solution:
if [:a, :b, :c, :d].include? variable
but this is not always functionally equivalent. I suppose Array#include? really looks to see if the object contains a variable in the list; it does not take into account that an object can implement its own equality test with def ==(other) .
As helpful commentators note below, this explanation is incorrect. include? uses == but uses the == method of the elements in the array. In my example, these are characters, not the == method of a variable. This explains why this does not match my first code example.
(Take, for example, the Rails' Mime::Type : request.format == :html implementation may return true, but [:html].include?(request.format) will return false since request.format is an instance of Mime :: Type, not a symbol.)
The best I have so far:
if [:a, :b, :c, :d].select {|f| variable == f}.any?
but for me it seems a little cumbersome. Anyone have the best deals?
syntax ruby
NeilS
source share