0

我正在阅读 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
4

3 回答 3

2

如果您查看Time.local的文档,

Time.local 不解析字符串。它希望您为年、月和日期传递一个单独的参数。当您传递像“1987,02,03”这样的字符串时,它会将其作为单个参数,即年份。然后它尝试将该字符串强制转换为整数 - 在本例中为 1982。

所以,基本上,你想把那个字符串分成年、月和日。有多种方法可以做到这一点。这是一个(可以缩短,但这是最清晰的方法)

year, month, date = date.split(/, */).map {|x| x.to_i}
Time.local(year, month, date)
于 2012-05-01T21:17:17.660 回答
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 调用,然后宾果游戏,干杯!

于 2012-05-05T13:33:40.317 回答
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(', '))
于 2012-05-01T21:30:04.833 回答