【发布时间】:2018-10-12 22:42:51
【问题描述】:
我的字符串是
str = "my string is this one"
我的数组是
arr = ["no", "nothing", "only", "is"]
所以,我的字符串在我的数组的值中包含 is,我想得到结果true
我该怎么做?
我想用include?遇见
【问题讨论】:
标签: ruby-on-rails arrays ruby string include
我的字符串是
str = "my string is this one"
我的数组是
arr = ["no", "nothing", "only", "is"]
所以,我的字符串在我的数组的值中包含 is,我想得到结果true
我该怎么做?
我想用include?遇见
【问题讨论】:
标签: ruby-on-rails arrays ruby string include
检查整个单词是否区分大小写:
(str.split & arr).any?
#⇒ true
不区分大小写:
[str.split, arr].map { |a| a.map(&:downcase) }.reduce(&:&).any?
#⇒ true
检查它是否包含arr 中的任何一个:
arr.any?(&str.method(:include?))
#⇒ true
【讨论】:
(str.downcase.split & arr.map(&:downcase)).any?
#=> false
如果已知所有字母大小写相同。
(str.split & arr).any?
#=> false
【讨论】:
这使用正则表达式。好消息是它是为您生成的 - 无需学习语法。其他好消息:它只遍历字符串一次。
re = Regexp.union(arr) #your own regular expression without screws or bolts
p re.match?(str) # => true
【讨论】:
str = "not"; arr = ["no"] 不应匹配。 (容易修复,不错的方法。)