@ndn 给出了这个问题的最佳答案,但我会建议另一种可能适用于其他问题的方法。
您给出的数组通常是通过在空格或标点符号上拆分字符串来获得的。例如:
s = "this is a test. I wonder if I can parse this text? Without any errors!"
s.scan /\w+|[.?!]/
#=> ["this", "is", "a", "test", ".", "I", "wonder", "if", "I", "can",
# "parse", "this", "text", "?", "Without", "any", "errors", "!"]
在这种情况下,您可能会发现以其他方式直接操作字符串更方便。例如,在这里,您可以首先使用带有正则表达式的String#split 将字符串s 分解为句子:
r1 = /
(?<=[.?!]) # match one of the given punctuation characters in capture group 1
\s* # match >= 0 whitespace characters to remove spaces
/x # extended/free-spacing regex definition mode
a = s.split(r1)
#=> ["this is a test.", "I wonder if I can parse this text?",
# "Without any errors!"]
然后拆分句子:
r2 = /
\s+ # match >= 1 whitespace characters
| # or
(?=[.?!]) # use a positive lookahead to match a zero-width string
# followed by one of the punctuation characters
/x
b = a.map { |s| s.split(r2) }
#=> [["this", "is", "a", "test", "."],
# ["I", "wonder", "if", "I", "can", "parse", "this", "text", "?"],
# ["Without", "any", "errors", "!"]]