尝试在 ruby 中搜索字符串以获取输入
我在使用 gets
搜索用户输入的字符串时遇到问题。概要如下:
puts "What are we searching for?"
search = gets
z=1
result = []
file = File.open('somefile.txt', 'r+')
file.each do |line|
if line.include?(search)
result << z
end
puts line
z+=1
end
puts "Found on line(s) #{result}
问题似乎出在 if line.include?(search)
上。当我将 (search)
替换为我正在搜索的值时(例如 ("example01")
),此脚本可以正常工作。但是当使用用户输入的值时——使用gets
,它似乎永远找不到它。 ("#{search}")
也不起作用。
我还尝试通过交换
if line.include?(search)
来
if line =~ Regexp.new(search)
使用正则表达式来解决相同的问题。
这是怎么回事?提前致谢。
I am having issues searching for a string input by the user using gets
. Here's the outline:
puts "What are we searching for?"
search = gets
z=1
result = []
file = File.open('somefile.txt', 'r+')
file.each do |line|
if line.include?(search)
result << z
end
puts line
z+=1
end
puts "Found on line(s) #{result}
The issue seems to be with if line.include?(search)
. When I replace (search)
with the value I am searching for--such as ("example01")
-- this script works fine. But when using the value input by the user--using gets
, it never seems to find it. ("#{search}")
doesn't work either.
I have also tried using regular expressions by swapping
if line.include?(search)
with
if line =~ Regexp.new(search)
with the same issue.
What is going on here? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试:
您当前的实现还存储您从输入添加的换行符。 chomp 将去掉 \n 或 \r。
Try :
Your current implementation also stores the line-return you are adding from the input. The chomp will get rid of the \n or \r.