=begin
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.
What do you think about something like 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
I know it's just a minor code vanity issue, but since it's one of Ruby's main features, I wanted to bring it up.
Since I can't fix the RD syntax error, here is the text again:
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.
What do you think about the following two solutions?
You explained you prefer str.included_in?(ary) or str.include?(ary) better because you "don't think it reads very nice".
I consider it very subjective. Could you elaborate if you really want the feature merged?
I am against str.include?([str1, str2]) because it might confuse users either str contains ALL of str1 and str2 or ANY of them. included_in? is better in that sense. But I feel it's ugly. I know it's VERY subjective. But you know, Ruby's design itself is very subjective to MY perspective, after all.
(First, sorry for my late reply, I somehow didn't receive notifications that my ticket was updated.)
Thank you very much for thinking about my proposal. I agree that it is very subjective and I probably also agree that str.include?([str1, str2]) is probably not a very good solution. However, I still think it would be a big code readability improvement to allow this direction of checking whether a string is included in a collection.
Let me describe an abstrac use case:
Many times I have an Array defined somewher of e.g. valid values, currencies, locales. Then I get a string from somewhere (maybe user input) and I want to check whether that string is within the valid values. Naturally I ask "Is this thing I just received included in the collection of all the valid things?". And it feels very unnatural having to ask instead "Does the collection of values include the thing I just got?".
I would be very glad if you would reconsider my proposal and I am convinced that it would improve the Syntax of the language.