ruby-on-rails - 将字符串作为 ruby​​ 中方法的条件传递

标签 ruby-on-rails ruby conditional whitelist

有没有办法通过字符串操作来创建条件。这是我尝试将字符串作为条件传递给 include? 方法的代码。

"hello eveyone in the house".include?(%w('hello' 'world' 'new\ york'    'place').join(" || ").to_s)

最佳答案

include? 的条件参数是不可能的,因为 include? 只接受字符串参数。

但是你可以这样写:

['hello', 'world', 'new york', 'place'].any? { |word|
  "hello everyone in the house".include?(word)
}

或者您可以从您的字符串生成一个正则表达式:

"hello eveyone in the house".match?(
  /#{['hello', 'world', 'new york', 'place'].join('|')}/
)

关于ruby-on-rails - 将字符串作为 ruby​​ 中方法的条件传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41352497/

相关文章:

conditional - 如何有条件地在 TAL (PHPTAL) 中添加 id 属性?

java - 如何在消息对话框中正确使用命令 "if"?

r - Shiny 的 R : Conditional style for textInput

ruby-on-rails - 覆盖 Rails to_param?

javascript - 如果不使用 `.js.erb` ,如何在 AJAX 请求后动态更新 DOM 元素?

javascript - 重定向时的 Rack-CORS 错误

ruby - 在 cygwin 上安装 webdriver gem 时出错

sql - 用于获取用户关联数据的 Rails 或 SQL 查询

ruby-on-rails - 如何从引擎中使用 FactoryGirl 工厂

ruby-on-rails - 来自单个 Rails 应用程序的多个数据库 : what's the state-of-the-art?