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

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

end_index = ['.', ','].member?(word[-1]) ? -3 : -2

However, this feels a little less elegant than most of things in Ruby. I'd rather write this code as

end_index = word[-1].is_in?('.', ',') ? -3 : -2

but I fail to find such method. Does it even exist? If not, any ideas as to why?


不是红宝石,但在ActiveSupport中:

characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true

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

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
链接地址: http://www.djcxy.com/p/25682.html

上一篇: 检查数组中是否存在元素而不迭代它

下一篇: 有没有反过来的'会员?' 方法在红宝石?