Ruby中是否有一个反向的“member?”方法?

10

我经常需要检查某个值是否属于某个集合。据我所知,人们通常使用 Enumerable#member? 来实现这一点。

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

然而,这种方法似乎不如 Ruby 中的大多数东西那样优雅。我更愿意以以下方式编写代码:

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

但我找不到这样的方法。它甚至存在吗?如果不存在,有任何想法原因是什么?


2
你也可以为成员方法使用别名:include?。在你的上下文中,这可能看起来更好:['。',','] .include?(word [-1])。 - Aliaksei Kliuchnikau
@Alex 谢谢,我差点忘了。 - Sergio Tulentsev
请参见 https://dev59.com/OnI-5IYBdhLWcg3wKVE9#10601055 - Marc-André Lafortune
5个回答

17

虽然不是在Ruby中,但在ActiveSupport中有这个功能:

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

10

您可以沿着这条线轻松定义它:

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

然后使用

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

或者定义

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

并使用作为

8.is_in?(0, 9, 15)   # false
8.is_in?(0, 8, 15)   # true

是的,我知道我可以这样做。但我宁愿不要把这段代码拖到每个新项目中。 :-) - Sergio Tulentsev
@Sergei Tulentsev:选择权在你手中。 - undur_gongor
把它放进一个宝石或其他什么东西里面就行了。 - Marnen Laibow-Koser

1

这不是你问题的答案,但也许是你问题的解决方案。

word 是一个字符串,对吗?

你可以使用正则表达式进行检查:

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

或者

end_index = word.match(/\A[\.,]/)  ? -3 : -2

是的,这可以解决这个具体的问题,但还有其他很多问题,比如[:admin, :moderator].include?(current_user.role)。 - Sergio Tulentsev

1
在你的特定情况下,有一个名为end_with?的函数,它可以接受多个参数。
"Hello.".end_with?(',', '.') #=> true

问题是关于一般情况的,我只是在代码中粘贴了最新的发生情况。但感谢您的提示,我不知道这种方法。 - Sergio Tulentsev

0

除非您处理的元素具有 === 的特殊含义,例如模块、正则表达式等,否则您可以使用 case

end_index = case word[-1]; when '.', ','; -3 else -2 end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接