我有一个简单的 Ruby 问题。我有一个字符串数组,我想确定该数组是否包含任何一个字符串的子字符串。例如:
a = ['cat','dog','elephant']
a.to_s.include?('ele')
这是最好的做法吗?
谢谢。
我有一个简单的 Ruby 问题。我有一个字符串数组,我想确定该数组是否包含任何一个字符串的子字符串。例如:
a = ['cat','dog','elephant']
a.to_s.include?('ele')
这是最好的做法吗?
谢谢。
a.any?
应该可以完成任务。
> a = ['cat','dog','elephant']
=> ["cat", "dog", "elephant"]
> a.any? { |s| s.include?('ele') }
=> true
> a.any? { |s| s.include?('nope') }
=> false
any?
检查,可能需要不同的问题,虽然简短的答案可能是:a.any? { |s| ['aba', 'ele'].any? { |t| s.include?(t) } }
。 - Shadwellhaystack.select { |str| str.include?('wat') || str.include?('pre') }
。 - Shiko这里还有另一种方法:如果你想获得那个受影响的字符串元素。
> a = ['cat','dog','elephant']
=> ["cat", "dog", "elephant"]
> a.grep(/ele/)
=> ["elephant"]
如果你只想要布尔值。
> a.grep(/ele/).empty?
=> false # it return false due to value is present
希望这对你有所帮助。
['cat','dog','elephant']
和'gel'
的true
或false
吗? - sepp2k