2016-06-25 3 views
1

그래서 누군가의 생일까지 며칠이 남았는지 알려주는 프로그램을 작성하려고합니다. 데이터를 그리는 텍스트 파일이 있습니다. 문제는 저장 방법이 작동하지 않아 출력 파일에 아무 것도 인쇄되지 않습니다. 미리 감사드립니다.Ruby : 빈 파일 출력

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 

답변

0

귀하의 Family.next_bday 아무것도 반환하지 않습니다 (더 정확하게하기 - 그것은 puts 반환 마지막 nil을 반환하는 것), 따라서 아무 것도 파일에 기록되지 않습니다.

다른 주 (직접 관련이없는) :

  1. , 단지
  2. Family::Member 일정 외모 더 많은 변수와 같은 첫 번째 호출에서 반환 값을 저장 두 번 Family.next_bday(response)를 호출의 어떤 이유로, 더 깨끗한 디자인에 없을 것 모든 것을 입력 파일 이름을 취하고 이니셜 라이저에서 데이터를 읽은 다음 인스턴스 변수에 저장하는 클래스로 만듭니다.