用ruby语言在字符串中查找数组元素

Ara*_*avi 0 ruby

在字符串中查找数组元素的有效且直接的代码是什么。例如:

a = Array['aaa', 'bbb', 'ccc', 'ddd', 'eee']

b = "This is the sample string with aaa , blah blah"

c = someFunction(b, a)
puts c
=> ['aaa']
Run Code Online (Sandbox Code Playgroud)

假设一个数组有 100 个元素,我想知道在字符串中找到了哪个数组元素。我应该匹配精确的词。所以xbbb,bbaa,...不匹配。

Ale*_*nko 5

我认为这是可能的解决方案之一:

def some_method(string, array)
  string.split & array
end

a = Array['aaa', 'bbb', 'ccc', 'ddd', 'eee']
b = "This is the sample string with aaa , blah blah"
> some_method(b, a)
=> ['aaa']

a = Array['aaa', 'bbb', 'ccc', 'ddd', 'eee']
b = "This is the sample string with xaaa , blah blah"
> some_method(b, a)
=> []
Run Code Online (Sandbox Code Playgroud)