true.to_i

L

Leslie Viljoen

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
 
A

Amos King

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.
 
K

Kalman Noel

Leslie Viljoen:
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?

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
 
R

Robert Klemme

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?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top