Skip to content

Instantly share code, notes, and snippets.

@unicornrainbow
Created September 21, 2011 04:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unicornrainbow/1231221 to your computer and use it in GitHub Desktop.
Save unicornrainbow/1231221 to your computer and use it in GitHub Desktop.
Ruby #in method.
# in extension to object.
#
class Object
# Returns true if the object sent #in is included in the argument list.
#
# Usage in conditionals:
#
# if 1.in 1, 2, 3
# puts "1 was included"
# end
#
# if "x".in *xyz
# puts "x was included"
# end
#
# if color.in :white, :gray, :black
# puts "#{color} isn’t a color."
# end
#
# It can also be used a safe alternative to ==.
#
# if 1.in 1.0
# puts "1 == 1.0 #=> true"
# end
#
# Using in like this avoids accidental assignment, like .eql?, but unlike .eql?
# has the same semantics as ==, which is often idea.
#
def in(*ary)
ary.include?(self)
end
end
@logankoester
Copy link

"(Am I the only person to have ever thought of this?)"

Nope :-) I like it though!

@unicornrainbow
Copy link
Author

Oh well... It's sooo sexy.

@unicornrainbow
Copy link
Author

Hey @maletor @jeyb @smcpherson, what do you guys think?

@unicornrainbow
Copy link
Author

Here's another implementation using recursion.

class Object
  def in(head, *tail)
    head == self || tail.any? && self.in(*tail)
  end
end

@Ajedi32
Copy link

Ajedi32 commented Jun 23, 2014

@blakefrost That implementation is probably less efficient, will break if you're searching for nil or false. (See Enumerable#any?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment