4

我是初学者,所以请原谅我这个相当简单的问题:

当我尝试运行以下代码时:

c = "hey there you you"
newarray = c.grep("you")
puts newarray

我在 ST2 中收到错误:<main>': undefined methodgrep' for "hey there you":String (NoMethodError)

但是,当我使用数组运行此代码时,它可以工作:

c = ["hey", "there", "you"]
newarray = c.grep("you")
puts newarray

我正在学习的书中的示例显示了将 grep 直接应用于字符串的示例,因此我不确定为什么会发生这种情况。任何人都可以启发我吗?

4

1 回答 1

4

grep 是一种可枚举的方法,因此它可以应用于数组和散列。"hey there you you" 是一个字符串,所以你正在寻找include?ormatchscan

"hey there you you".match 'you'
"hey there you you".scan 'you' # returns 2 results
于 2013-02-12T06:10:45.060 回答