Ruby:文件输出空白

时间:2016-06-25 13:24:15

标签: ruby file-io module

所以我正在尝试建立一个程序,告诉我在某人生日那天剩下多少天。我有一个文本文件,我正在从中提取数据。问题是保存方法由于某种原因无法正常工作,并且没有任何内容正在打印到输出文件。非常感谢你!

require 'date'

Person = Struct.new(:name, :bday)

module Family

  Member = Hash.new

    File.readlines("bday_info.txt").each do |line|
      name, bday = line.split(',')
      person = Person.new(name, bday)
      Member[name] = bday
    end

    def self.next_bday(name)
      birthday = Date.parse(Family::Member[name])
      this_year = Date.new(Date.today.year, birthday.month, birthday.day)
      next_year = Date.new(Date.today.year + 1, birthday.month, birthday.day)
      if this_year > Date.today
        puts "\n#{(this_year - Date.today).to_i} days to #{name}'s birthday"
      else
        puts "\n#{(next_year - Date.today).to_i} days to #{name}'s birthday"
      end
    end

    def self.save(name)
      File.open("days_left.txt", "w") do |file|
        file.puts "#{next_bday(name)}"
      end
    end

end

loop do
  puts "\nName:"
  response = gets.chomp.capitalize
  if response.downcase == "quit"
    break
  elsif Family::Member.has_key?("#{response}") == false
    puts "\nYou ain't on the list"
  else
  Family.next_bday(response)
  Family.save(response) #WHY IS THIS LINE NOT WORKING???
  end
end

1 个答案:

答案 0 :(得分:0)

你的Family.next_bday没有返回任何内容(更确切地说 - 它返回nil最后puts返回),因此没有任何内容写入文件。

其他说明(不直接相关):

  1. 没有理由两次调用Family.next_bday(response),只保存第一次调用的返回值
  2. Family::Member常量看起来更像一个变量,更干净的设计将使整个事物成为一个接受输入文件名的类,在初始化器中读取数据然后存储到实例变量中