这是给出的问题:
练习2.1
给定一个包含多行的文本文件,编写一个程序 打印具有最大字符数和数量的行 它有的字符。假设输入文件具有明显的最大值( 即,只有一行具有最大字符数。)
这是我正确的解决方案:
def file
infile = File.open('example.txt', 'r')
max = -1
maxln = ''
while (line = infile.gets)
size = line.chomp.size
if max < size
max = size
maxln = line
end
end
infile.close
puts maxln
puts max
end
file
但是,我想稍微玩一下,所以我将代码分解成不同的功能:
def initialize(max = -1, maxln = '')
@max = max
@maxln = ''
end
def defining_max
if @max < @size
@max, @maxln = @size, @line
end
end
def building_max
infile = File.open('example.txt', 'r')
while (line = infile.gets)
@size = line.chomp.size
defining_max
end
infile.close
puts @maxln
puts @max
end
building_max
在building_max
我尝试拨打defining_max
。我怎么做?而且,我是否正确地将代码分解为不同的函数?
这是我得到的错误:
c2e1.rb:95: warning: redefining Object#initialize may cause infinite loop
c2e1.rb:101:in `defining_max': undefined method `<' for nil:NilClass (NoMethodError)
from c2e1.rb:110:in `building_max'
from c2e1.rb:117:in `<main>'
答案 0 :(得分:2)
mr_sudaca是对的,你的@max总是为零..
也许你想尝试一下:
class Discover
def initialize
@max = 0
@maxln = ''
end
def maxNumberOf file
infile = File.open(file, 'r')
while (line = infile.gets)
defining_max line
end
infile.close
@maxln
end
private
def defining_max line
size = line.chomp.size
if @max < size
@max = size
@maxln = line
end
end
end
t = Discover.new
puts t.maxNumberOf 'example.txt'