How to compare a string against multiple other strings

后端 未结 3 1840
忘了有多久
忘了有多久 2020-12-15 16:23

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

myString.eql?([\"string1\",\"st         


        
相关标签:
3条回答
  • 2020-12-15 16:42
    ["string1","string2","string3"].include? myString
    
    0 讨论(0)
  • 2020-12-15 16:58

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

    %w(string1 string2 string3).include?(myString)
    
    0 讨论(0)
  • 2020-12-15 17:01

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

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

    Then

    myString.among?("string1","string2","string3")
    
    0 讨论(0)
提交回复
热议问题