在Ruby中,如何判断字符串是否不在数组中?

And*_*rew 33 ruby arrays

在Ruby中,如果字符串不在选项数组中,我将如何返回true?

# pseudo code
do_this if current_subdomain not_in ["www", "blog", "foo", "bar"]
Run Code Online (Sandbox Code Playgroud)

...或者你知道一个更好的方法吗?

Mik*_*wis 55

do_this unless  ["www", "blog", "foo", "bar"].include?(current_subdomain)
Run Code Online (Sandbox Code Playgroud)

要么

do_this if not ["www", "blog", "foo", "bar"].include?(current_subdomain)
Run Code Online (Sandbox Code Playgroud)

我正在使用Array #include?方法.

然而,使用unless是一个相当大的红宝石成语.

  • `do_this if !["www", "blog", "foo", "bar"].include?(current_subdomain)` 有效。对于复杂的条件,示例一:`&& !` 示例二:`and not`。 (2认同)

小智 7

您可以尝试exclude?方法而不是include?

例子:

do_this if ["www", "blog", "foo", "bar"].exclude?(current_subdomain)
Run Code Online (Sandbox Code Playgroud)

希望这有助于...谢谢

  • 排除?仅来自 ActiveSupport 库。核心 Ruby 未正式支持。 (3认同)