Skip to content

Instantly share code, notes, and snippets.

@fredwu
Created August 6, 2012 14:32
Show Gist options
  • Save fredwu/3274847 to your computer and use it in GitHub Desktop.
Save fredwu/3274847 to your computer and use it in GitHub Desktop.
ruby/rails wtf
# ruby 1.9.3-p194 + rails 3.2.6
Date.new.step(Date.new, 1.second).map{}
#=> TypeError: expected numeric
Date.new.step(Date.new, 1.second.to_i).map{}
#=> [nil]
Date.new.step(Date.new, 1).map{}
#=> [nil]
# ruby 1.9.2-p290 + rails 3.2.6
Date.new.step(Date.new, 1.second).map{}
#=> [nil]
Date.new.step(Date.new, 1.second.to_i).map{}
#=> [nil]
Date.new.step(Date.new, 1).map{}
#=> [nil]
@fredwu
Copy link
Author

fredwu commented Aug 6, 2012

On both 1.9.2 and 1.9.3, 1.second returns Fixnum.

@rkh
Copy link

rkh commented Aug 6, 2012

It doesn't. It only pretends it does:

Fixnum === 1.second # => false

@fredwu
Copy link
Author

fredwu commented Aug 6, 2012

@rkh Ah I see! Any insights on what the cause is for the different behaviour on 1.9.2 and 1.9.3?

@rkh
Copy link

rkh commented Aug 6, 2012

@fredwu 1.9.3 probably follows convention and calls to_int on the argument.

@tenderlove
Copy link

@fredwu I don't think this has anything to do with Rails. It seems like Date in ruby-core has changed. My hunch is that someone stopped calling NUM2INT, which will attempt to convert your object to an integer.

Can you try this code on 1.9.2 vs 1.9.3?

require 'date'

class Foo
  def to_i
    1
  end
end

Date.new.step(Date.new, Foo.new).each { }

@rkh
Copy link

rkh commented Aug 6, 2012

Oh, yeah, what I said but the other way around: 1.9.2 used to call it, and it was to_i, not to_int.

@fredwu
Copy link
Author

fredwu commented Aug 7, 2012

Thanks @rkh and @tenderlove!

@tenderlove I've tried your snippet and on both 1.9.2 and 1.9.3, this is the result:

TypeError: no implicit conversion from nil to integer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment