我是初学者所以请原谅我提出这个相当简单的问题:
当我尝试运行以下代码时:
c = "hey there you you"
newarray = c.grep("you")
puts newarray
我在 ST2 中收到错误:<main>': undefined method
grep' for "hey there you you":String (NoMethodError)
但是,当我使用数组运行这段代码时,它起作用了:
c = ["hey", "there", "you"]
newarray = c.grep("you")
puts newarray
我正在学习的书中的示例显示了将 grep 直接应用于字符串的示例,所以我不确定为什么会这样。谁能赐教一下?
最佳答案
grep 是一种可枚举的方法,因此它可以应用于数组和散列。 "hey there you you"是一个字符串,因此您正在寻找 include?
或 match
或 scan
"hey there you you".match 'you'
"hey there you you".scan 'you' # returns 2 results
关于ruby-on-rails - 我似乎无法 grep 处理纯字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14826500/