是否存在逆“成员”?红宝石中的方法?
我经常发现自己在检查某个值是否属于某个集合。据我了解,人们通常使用 Enumerable#member?
来实现此目的。
end_index = ['.', ','].member?(word[-1]) ? -3 : -2
然而,这感觉比 Ruby 中的大多数东西不太优雅。我宁愿编写这段代码
end_index = word[-1].is_in?('.', ',') ? -3 : -2
,但我找不到这样的方法。它真的存在吗?如果没有,有什么想法可以解释为什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不在 ruby 中,但在 ActiveSupport 中:
Not in ruby but in ActiveSupport:
您可以沿着这条线轻松定义它:
然后使用 as
或定义
并使用 as
You can easily define it along this line:
and then use as
or define
and use as
不是您问题的答案,但也许是您问题的解决方案。
word
是一个字符串,不是吗?您可以使用正则表达式检查:
或
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:
or
在您的具体情况下,有 end_with?,它需要多个参数。
In your specific case there's end_with?, which takes multiple arguments.
除非您正在处理对
===
具有特殊含义的元素,例如模块、正则表达式等,否则您可以使用case
做得很好。Unless you are dealing with elements that have special meaning for
===
like modules, regexes, etc., you can do pretty much well withcase
.