【问题标题】:Trying to search a string for a gets input in ruby尝试在字符串中搜索 a 获取 ruby​​ 中的输入
【发布时间】:2011-12-08 22:58:10
【问题描述】:

我在搜索用户使用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)

同样的问题。

这里发生了什么?提前致谢。

【问题讨论】:

    标签: ruby regex include gets


    【解决方案1】:

    试试:

    search = gets.chomp
    

    您当前的实现还存储了您从输入中添加的换行符。 chomp 将摆脱 \n 或 \r。

    【讨论】:

    • 这是一个非常常见的 Ruby 问题。太常见了,我不明白为什么没有getstring 可以自动执行...
    • 好吧,如果那不是红宝石试纸,我不知道是什么。谢谢卡西姆。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2019-12-02
    • 2015-01-28
    • 2020-05-05
    • 1970-01-01
    相关资源
    最近更新 更多