Zep*_*434 5 ruby ruby-on-rails
我是初学者,所以请原谅我提出这个相当简单的问题:
当我尝试运行以下代码时:
c = "hey there you you"
newarray = c.grep("you")
puts newarray
Run Code Online (Sandbox Code Playgroud)
我在 ST2 中收到错误:<main>': undefined methodgrep' for "hey there you you":String (NoMethodError)
但是,当我使用数组运行此代码时,它会起作用:
c = ["hey", "there", "you"]
newarray = c.grep("you")
puts newarray
Run Code Online (Sandbox Code Playgroud)
我正在学习的书中的示例显示了 grep 直接应用于字符串的示例,所以我不确定为什么会发生这种情况。谁能启发我吗?
grep 是一种可枚举方法,因此它可以应用于数组和哈希。“嘿,你你”是一个字符串,所以你正在寻找include?或match或scan
"hey there you you".match 'you'
"hey there you you".scan 'you' # returns 2 results
Run Code Online (Sandbox Code Playgroud)