是否存在逆“成员”?红宝石中的方法?

发布于 2024-12-15 07:35:02 字数 321 浏览 0 评论 0原文

我经常发现自己在检查某个值是否属于某个集合。据我了解,人们通常使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

月亮是我掰弯的 2024-12-22 07:35:02

不在 ruby​​ 中,但在 ActiveSupport 中

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

Not in ruby but in ActiveSupport:

characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true
一抹淡然 2024-12-22 07:35:02

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

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

然后使用 as

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

并使用 as

8.is_in?(0, 9, 15)   # false
8.is_in?(0, 8, 15)   # 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
顾北清歌寒 2024-12-22 07:35:02

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

word 是一个字符串,不是吗?

您可以使用正则表达式检查:

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

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

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
雨轻弹 2024-12-22 07:35:02

在您的具体情况下,有 end_with?,它需要多个参数。

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

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

"Hello.".end_with?(',', '.') #=> true
迷爱 2024-12-22 07:35:02

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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文