开发者

Ruby date arithmetic error - "can't convert Date into an exact number (TypeError)"

I have the following Ruby program:

require 'date'

class Person

 def initialize(name, dob)
  @name = name
  @dob = dob
 end

 def age
  Ti开发者_StackOverflowme.now - @dob
 end

 def marry(someone)
  "Life: " + age.to_s
 end

end

fred = Person.new('Fred', Date.new(1934, 4, 16))
p fred
p fred.age.to_s
p fred.marry(1)

But ruby 1.9.2 gives error:

#<Person:0x2afab78 @name="Fred", @dob=#<Date: 1934-04-16 (4855087/2,0,2299161)>>
test1.rb:11:in `-': can't convert Date into an exact number (TypeError)
        from test1.rb:11:in `age'
        from test1.rb:22:in `<main>'

What am I doing wrong? TIA


You're trying to subtract a Date from a Time:

ruby-1.9.1-p378 > Time.now - Date.today
TypeError: can't convert Date into Float

But you can safely subtract a date from a date:

ruby-1.9.1-p378 > Date.today - Date.new(1900,1,1)
 => (40466/1) 

ruby-1.9.1-p378 > (Date.today - Date.new(1900,1,1)).to_f / 365 # years
 => 110.865753424658 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜