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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@blakefrost That implementation is probably less efficient, will break if you're searching for
nil
orfalse
. (See Enumerable#any?)