Created
August 30, 2011 16:02
-
-
Save jhilden/1181246 to your computer and use it in GitHub Desktop.
[Ruby] String.include?([Array])
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
# I find myself constantly wanting to check whether one string is included within an array of strings. | |
# It is certainly possible (and also fast) to do that in Ruby with something like this: ["foo", "bar"].include?("foo") | |
# But I don't think it reads very nice :( | |
# Because what I actually want to test is, whether my string is included in the array and NOT the other way around. | |
# - Do you have the same problem? | |
# - What do you think about the following two solutions? | |
class String | |
# create a new method | |
def included_in?(array) | |
array.include?(self) | |
end | |
# -- OR -- | |
# change the current String#include? method | |
def include?(parameter) | |
if parameter.is_a? Array | |
parameter.include?(self) | |
else | |
super | |
end | |
end | |
end |
PS: you should think about submitting it as a patch for Ruby or Active Support
Thanks for your feedback. I gave it a try to submit it as a Ruby feature request: https://bugs.ruby-lang.org/issues/6365
Great idea!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was looking for a solution to this problem for the same reason as you - pure code vanity :) I like the
include_any?
method but I think I will name minein?
so I could write it like"foo".in? %w(baz boo bar foo)