我正在研究Chris Pine的Ruby书,我有点困惑为什么我的代码不能正常工作。
我有一个名为birthdays.txt
的文件,它有大约10行文字,类似于:
Andy Rogers, 1987, 02, 03
等
我的代码如下:
hash = {}
File.open('birthdays.txt', "r+").each_line do |line|
name, date = line.chomp.split( /, */, 2 )
hash[name] = date
end
puts 'whose birthday would you like to know?'
name = gets.chomp
puts hash[name]
puts Time.local(hash[name])
我的问题是,为什么最后一行代码Time.local(hash[name])
会产生这个输出?:
1987-01-01 00:00:00 +0000
而不是:
1987-02-03 00:00:00 +0000
答案 0 :(得分:2)
如果查看Time.local的文档,
Time.local不解析字符串。它希望您为年,月和日期传递单独的参数。当您传递像“1987,02,03”这样的字符串时,需要将其作为单个参数,即年份。然后它尝试将该字符串强制转换为整数 - 在本例中为1982。
所以,基本上,你想把那个字符串分成年,月和日。有多种方法可以做到这一点。这是一个(它可以缩短,但这是最明确的方式)
year, month, date = date.split(/, */).map {|x| x.to_i}
Time.local(year, month, date)
答案 1 :(得分:0)
line = "Andy Rogers, 1987, 02, 03\n"
name, date = line.chomp.split( /, */, 2 ) #split (', ', 2) is less complex.
#(Skipping the hash stuff; it's fine)
p date #=> "1987, 02, 03"
# Time class can't handle one string, it wants: "1987", "02", "03"
# so:
year, month, day = date.split(', ')
p Time.local(year, month, day)
# or do it all at once (google "ruby splat operator"):
p Time.local(*date.split(', '))
答案 2 :(得分:0)
hash = {}
File.open('birthdays.txt').each_line do |line|
line = line.chomp
name, date = line.split(',',2)
year, month, day = date.split(/, */).map {|x| x.to_i}
hash[name] = Time.local(year, month, day)
end
puts 'Whose birthday and age do you want to find out?'
name = gets.chomp
if hash[name] == nil
puts ' Ummmmmmmm, dont know that one'
else
age_secs = Time.new - hash[name]
age_in_years = (age_secs/60/60/24/365 + 1)
t = hash[name]
t.strftime("%m/%d/%y")
puts "#{name}, will be, #{age_in_years.to_i} on #{t.strftime("%m/%d/")}"
end
必须在程序的早期移动Time.local调用,然后宾果游戏,为人欢呼!