【问题标题】:ruby: undefined method exclude?红宝石:未定义的方法排除?
【发布时间】:2019-11-06 08:54:08
【问题描述】:

我尝试使用相反的包含方法?在 ruby​​ 中,即“string|array.exclude?”,这是我在交互式 ruby​​ 上的代码。

this = "nice"
puts this.exclude? "n"

但是,它总是声明一个错误。

Traceback(最近一次通话最后一次):

    4: from C:/Ruby26-x64/bin/irb.cmd:31:in `<main>'
    3: from C:/Ruby26-x64/bin/irb.cmd:31:in `load'
    2: from C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
    1: from (irb):14

NoMethodError(未定义方法 `exclude?' for "nice":String)

我研究了很多,但没有找到解决方案。我想知道它是否只发生在我身上,这让我非常恼火。

谁能帮帮我。 非常感谢。

【问题讨论】:

  • !"string".include?(pattern) 不适合你?

标签: ruby


【解决方案1】:

String#exclude? 是 activesupport gem 的一部分,它与每个 rails 项目一起安装。它不包含在 ruby​​ 的标准库中。但是这个方法是quite simple

def exclude?(string)
  !include?(string)
end

【讨论】:

  • 另外,您可以将 activesupport 直接加载到您的 ruby​​ 项目中。根据您的需要,可能建议只加载您真正需要的核心扩展,如本指南所述:guides.rubyonrails.org/active_support_core_extensions.html
  • 你需要 2 个模式,一个要匹配的字符串和一个模式,应该类似于 !string.include?(pattern) 或 !string[/regexp/],或者......你需要注入将该方法放入 String 类中,我不会那样做...
【解决方案2】:

试试这个

unless this.include?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 2011-02-28
    相关资源
    最近更新 更多