开发者

Trying to search a string for a gets input in ruby

开发者 https://www.devze.com 2023-04-13 05:12 出处:网络
I am having issues searching for a string input by the user using gets. Here\'s the outline: puts \"What are we searching for?\"

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开发者_Python百科=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.


Try :

search = gets.chomp

Your current implementation also stores the line-return you are adding from the input. The chomp will get rid of the \n or \r.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号