Is there an inverse 'member?' method in ruby?

前端 未结 5 1002
礼貌的吻别
礼貌的吻别 2020-11-30 12:55

I often find myself checking if some value belongs to some set. As I understand, people normally use Enumerable#member? for this.

end_index = [\         


        
相关标签:
5条回答
  • 2020-11-30 13:05

    Not in ruby but in ActiveSupport:

    characters = ["Konata", "Kagami", "Tsukasa"]
    "Konata".in?(characters) # => true
    
    0 讨论(0)
  • 2020-11-30 13:13

    You can easily define it along this line:

    class Object
      def is_in? set
        set.include? self
      end
    end
    

    and then use as

    8.is_in? [0, 9, 15]   # false
    8.is_in? [0, 8, 15]   # true
    

    or define

    class Object
      def is_in? *set
        set.include? self
      end
    end
    

    and use as

    8.is_in?(0, 9, 15)   # false
    8.is_in?(0, 8, 15)   # true
    
    0 讨论(0)
  • 2020-11-30 13:24

    Unless you are dealing with elements that have special meaning for === like modules, regexes, etc., you can do pretty much well with case.

    end_index = case word[-1]; when '.', ','; -3 else -2 end
    
    0 讨论(0)
  • 2020-11-30 13:25

    In your specific case there's end_with?, which takes multiple arguments.

    "Hello.".end_with?(',', '.') #=> true
    
    0 讨论(0)
  • 2020-11-30 13:30

    Not the answer for your question, but perhaps a solution for your problem.

    word is a String, isn't it?

    You may check with a regex:

    end_index = word =~ /\A[\.,]/  ? -3 : -2
    

    or

    end_index = word.match(/\A[\.,]/)  ? -3 : -2
    
    0 讨论(0)
提交回复
热议问题