Created
September 21, 2011 04:03
-
-
Save unicornrainbow/1231221 to your computer and use it in GitHub Desktop.
Ruby #in method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Oh well... It's sooo sexy.
Hey @maletor @jeyb @smcpherson, what do you guys think?
Here's another implementation using recursion.
class Object
def in(head, *tail)
head == self || tail.any? && self.in(*tail)
end
end
@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
"(Am I the only person to have ever thought of this?)"
Nope :-) I like it though!