我正在尝试编写一个简单的命令行程序,让我可以跟踪在学习期间我分心的次数。
我运行此代码时遇到参数错误,说我的file.open
包含无效参数。如果我想用时间戳为每个new_session
文件命名,那么这将是一个简单的解决方案吗?
def first_question
puts "Would you like to start a new session?"
answer = gets.chomp
answer = answer.downcase
if answer == "yes"
new_session
else
puts "Ok. Would you like to review a previous session?"
prev_session = gets.chomp
prev_session.downcase
if prev_session == "yes"
#GET AND REVIEW PREVIOUS SESSIONS
elsif prev_session == "no"
puts "Well if you don't want a new session, and you don't want to review your old sessions, then you're SOL."
else
"That's not an acceptable response."
first_question
end
end
end
def new_session
distractions = 0
d = File.open("Session"+Time.now.to_s , 'w'){|f| f.write(distractions) }
puts "What would you like to do (add track(s) or review tracks)?"
request = gets.chomp
request.downcase
if request == "add track"
distractions = distractions.to_i + 1
puts "You have #{distractions} tracks in this session."
elsif request == "add tracks"
puts "How many times have you been distracted since we last met?"
answer = gets.chomp
distractions = distractions.to_i + answer.to_i
puts "You have #{distractions} tracks."
elsif request == "review tracks"
puts distractions
end
File.open( d , 'w') {|f| f.write(distractions) }
end
first_question
答案 0 :(得分:1)
您的大多数代码都是混乱和多余的。但是,你所指的问题来自:
d = File.open("Session"+Time.now.to_s , 'w'){|f| f.write(distractions) }
d
将是写入文件的字节数,因此是Fixnum。你不能打开你在函数的最后一行尝试做的Fixnum。
此外,
request = gets.chomp
request.downcase
这里的第二行什么也没做。
答案 1 :(得分:0)
您有两个File.open
语句:
d = File.open("Session"+Time.now.to_s , 'w'){|f| f.write(distractions) }
和
File.open( d , 'w') {|f| f.write(distractions) }
你的错误代码会告诉你哪一个是错误的,但是,通过查看它们,我会说它是第二个。
d
将为第一个File.open
分配块的结果,这将是f.write(distractions)
的结果:
File.open
文档说:
将从File.open返回块的值。
File.write
文档说:
返回写入的字节数。
结果,您为d
分配了多个字节,然后尝试创建一个文件名为整数的文件,这是一个错误,因为文件名必须是一个字符串。
这会导致更大的问题,也就是说,你的代码毫无意义。
d = File.open("Session"+Time.now.to_s , 'w'){|f| f.write(distractions) }
将0
写入"Session"+Time.now.to_s
创建的文件。 request.downcase
将request
的内容转换为小写并立即将其丢弃。也许你的意思是request.downcase!
,但最好写一下:
request = gets.chomp
request.downcase
如:
request = gets.chomp.downcase
distractions = distractions.to_i + 1
? distractions
已经0
,这是一个Fixnum。您正在使用to_i
将Fixnum转换为整数,然后将其加1。只需:
distractions += 1
distractions = distractions.to_i + answer.to_i
应该是:
distractions += answer.to_i
File.open( d , 'w') {|f| f.write(distractions) }
,因为尝试写入具有整数名称的文件,不会更新原始文件。如果成功,它将写入一个全新的文件,最终会覆盖以前创建的文件,这是将单个0
写入磁盘的结果。相反,d
应该是先前创建的文件的名称。
考虑一下:
def new_session
distractions = 0
puts "What would you like to do (add track(s) or review tracks)?"
request = gets.chomp.downcase
case request
when "add track"
distractions += 1
puts "You have #{distractions} tracks in this session."
when "add tracks"
puts "How many times have you been distracted since we last met?"
distractions += gets.chomp.to_i
puts "You have #{distractions} tracks."
when "review tracks"
puts distractions
end
File.write( "Session" + Time.now.to_s, distractions)
end
此代码更清晰,现在更有意义。