如何将字符串与多个其他字符串进行比较

时间:2021-03-30 14:16:48

Is there a method that let me compare one String with multiple others in Ruby? I really would like to do something like this:

有没有一种方法可以让我在Ruby中比较一个String和多个其他?我真的想做这样的事情:

myString.eql?(["string1","string2","string3"])

3 个解决方案

#1


48  

["string1","string2","string3"].include? myString

#2


14  

You could use Array#include? to see if the array includes the string:

你可以使用Array #include吗?查看数组是否包含字符串:

%w(string1 string2 string3).include?(myString)

#3


10  

I find myself wanting this a lot, so I added a String method to be able to do it more idiomatically:

我发现自己想要这么多,所以我添加了一个String方法,以便能够更加惯用:

class String
  def among?(*array)
    array.flatten.include?(self)
  end
end

Then

然后

myString.among?("string1","string2","string3")

#1


48  

["string1","string2","string3"].include? myString

#2


14  

You could use Array#include? to see if the array includes the string:

你可以使用Array #include吗?查看数组是否包含字符串:

%w(string1 string2 string3).include?(myString)

#3


10  

I find myself wanting this a lot, so I added a String method to be able to do it more idiomatically:

我发现自己想要这么多,所以我添加了一个String方法,以便能够更加惯用:

class String
  def among?(*array)
    array.flatten.include?(self)
  end
end

Then

然后

myString.among?("string1","string2","string3")