。包括?读取txt文件时不触发
.include? is not triggered when reading a txt file
我的印象是下面的代码 应该 return 搜索项 word
或消息 no match
- 如所示由三元运算符。我无法诊断 where/why 包括?方法无效。
class Foo
def initialize(word)
@word=word
end
def file_open
IO.foreach('some_file.txt') do |line|
line.include?(@word) ? "#{@word}" : "no match"
end
end
end
print "search for: "
input = gets.chomp.downcase
x = Foo.new(input)
puts x.file_open
input
存在于 some_file.txt
中。我的三元运算符语法也是正确的。 IO 可以很好地读取文本(我也尝试了 File.open() 并遇到了同样的问题)。所以我的 include?
方法肯定有误。
您需要控制 returned 值。 file_open
上面定义的总是 return nil
。三元将被正确执行,但它的值没有做任何事情。相反,您可以执行以下操作:
class Foo
def initialize(word)
@word=word
end
def file_open
IO.foreach('some_file.txt') do |line|
return line if line.include?(@word)
end
return "no match"
end
end
我的印象是下面的代码 应该 return 搜索项 word
或消息 no match
- 如所示由三元运算符。我无法诊断 where/why 包括?方法无效。
class Foo
def initialize(word)
@word=word
end
def file_open
IO.foreach('some_file.txt') do |line|
line.include?(@word) ? "#{@word}" : "no match"
end
end
end
print "search for: "
input = gets.chomp.downcase
x = Foo.new(input)
puts x.file_open
input
存在于 some_file.txt
中。我的三元运算符语法也是正确的。 IO 可以很好地读取文本(我也尝试了 File.open() 并遇到了同样的问题)。所以我的 include?
方法肯定有误。
您需要控制 returned 值。 file_open
上面定义的总是 return nil
。三元将被正确执行,但它的值没有做任何事情。相反,您可以执行以下操作:
class Foo
def initialize(word)
@word=word
end
def file_open
IO.foreach('some_file.txt') do |line|
return line if line.include?(@word)
end
return "no match"
end
end