Skip to content

Instantly share code, notes, and snippets.

@jhilden
Created August 30, 2011 16:02
Show Gist options
  • Save jhilden/1181246 to your computer and use it in GitHub Desktop.
Save jhilden/1181246 to your computer and use it in GitHub Desktop.
[Ruby] String.include?([Array])
# 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
@chrisbloom7
Copy link

PS: you should think about submitting it as a patch for Ruby or Active Support

@jhilden
Copy link
Author

jhilden commented Apr 26, 2012

Thanks for your feedback. I gave it a try to submit it as a Ruby feature request: https://bugs.ruby-lang.org/issues/6365

@gdelfino
Copy link

Great idea!

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