True.to_i

Hello

I am processing database rows and I see that there are “bit” columns
that come out of ActiveRecord as true or false. I wanted binary digits
so I did this:

class FalseClass
def to_i
0
end
end

class TrueClass
def to_i
1
end
end

…which may or may not be really dumb. So is it really dumb?


Man’s unfailing capacity to believe what he prefers to be true rather
than what the evidence shows to be likely and possible has always
astounded me. We long for a caring Universe which will save us from
our childish mistakes, and in the face of mountains of evidence to the
contrary we will pin all our hopes on the slimmest of doubts. God has
not been proven not to exist, therefore he must exist.

  • Prokhor Zakharov

I don’t see a problem with it. There is no to_i for either class so
you wouldn’t be overwriting any functionality there. I would say gtg.

Leslie V.:

class TrueClass
def to_i
1
end
end

.which may or may not be really dumb. So is it really dumb?

It isn’t really dumb, but you can get into problems when debugging code
independent of your ActiveRecord. The issue is basically that you place
the
solution of a problem of your record into another class, where it does
not
belong. I’d suggest something like (untested)

class MyRecord
def my_column_as_int
my_column? ? 1 : 0
end
end

or even (untested as well)

class MyRecord

alias my_column_as_bool my_column
def my_column
my_column_as_bool ? 1 : 0
end

alias my_column_as_bool= my_column=
def my_column=(val)
val = false if val == 0
self.my_column_as_bool = val
end

end

Kalman

On 30.10.2006 16:00, Leslie V. wrote:

end

class TrueClass
def to_i
1
end
end

.which may or may not be really dumb. So is it really dumb?

Remember that a lot of other values are considered true so converting
them will either not work (exception) or create all sorts of other weird
effects if you try to generalize this pattern.

I would prefer a custom conversion function

def bit_int(x) x ? 1 : 0 end

Kind regards

robert