Rails bitten by Ruby’s nil.to_f

I guess I’m still new enough to Ruby that this does not make sense to me:

>> nil.to_f
=> 0.0

Magically, from nothing, you have something. I suppose it might be convenient in places, but today I ran into a minor bug in Rails that causes problems when trying to get the average of a column that doesn’t have any entries.

So what is the reasoning behind nil.to_f being 0.0 (and nil.to_i being 0, to_s being “”), anyway?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s