Ruby on Rails里,如何将字符串作为方法条件?

2026-04-10 07:352阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计269个文字,预计阅读时间需要2分钟。

Ruby on Rails里,如何将字符串作为方法条件?

没有方法可以通过字符串操作直接创建条件。下面是一个简化的版本,不使用数组和复杂的操作:

可以通过字符串拼接和条件判断来实现条件传递。例如,使用 `include?` 方法检查字符串是否包含特定子串。方法示例:`hello everyone in the house.include?(hello) ? '包含条件的参数' : '不包含条件的参数'`。

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

"hello eveyone in the house".include?(%w('hello' 'world' 'new\ york' 'place').join(" || ").to_s) 包含条件的参数?是不可能的,因为包括?只接受一个字符串参数.

但你可以这样写:

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

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

Ruby on Rails里,如何将字符串作为方法条件?

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

本文共计269个文字,预计阅读时间需要2分钟。

Ruby on Rails里,如何将字符串作为方法条件?

没有方法可以通过字符串操作直接创建条件。下面是一个简化的版本,不使用数组和复杂的操作:

可以通过字符串拼接和条件判断来实现条件传递。例如,使用 `include?` 方法检查字符串是否包含特定子串。方法示例:`hello everyone in the house.include?(hello) ? '包含条件的参数' : '不包含条件的参数'`。

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

"hello eveyone in the house".include?(%w('hello' 'world' 'new\ york' 'place').join(" || ").to_s) 包含条件的参数?是不可能的,因为包括?只接受一个字符串参数.

但你可以这样写:

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

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

Ruby on Rails里,如何将字符串作为方法条件?

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