0

私はChrisPineの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)に強制変換しようとします。

したがって、基本的には、その文字列を年、月、日にスライスする必要があります。これを行うには複数の方法があります。これが1つです(短くすることもできますが、これが最も明確な方法です)

year, month, date = date.split(/, */).map {|x| x.to_i}
Time.local(year, month, date)
于 2012-05-01T21:17:17.660 に答える
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 に答える
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 に答える