Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

I have the following Ruby program:

require 'date'

class Person

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

 def age
  Time.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

like image 799
Fred Avatar asked Oct 17 '10 18:10

Fred


1 Answers

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 
like image 188
Mark Rushakoff Avatar answered Nov 14 '22 21:11

Mark Rushakoff