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

梦想的初衷 提交于 2019-11-26 11:30:39

问题


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?


回答1:


Not in ruby but in ActiveSupport:

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



回答2:


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



回答3:


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



回答4:


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

"Hello.".end_with?(',', '.') #=> true



回答5:


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


来源:https://stackoverflow.com/questions/8133397/is-there-an-inverse-member-method-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!