# Converting TrueClass / FalseClass to integer

**URL:** <https://www.ruby-forum.com/t/converting-trueclass-falseclass-to-integer/185816>\
**Category:** Rails\
**Created:** [March 26, 2010, 5:12pm UTC](https://www.ruby-forum.com/t/converting-trueclass-falseclass-to-integer/185816 "2010-03-26T17:12:09Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![paerez](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/5fc32e/32.png) [@paerez](https://www.ruby-forum.com/u/paerez)\
**Post date:** [March 26, 2010, 5:12pm UTC](https://www.ruby-forum.com/t/converting-trueclass-falseclass-to-integer/185816/1 "2010-03-26T17:12:09Z")

</div>

Hello.

I’m trying to figure out if there is an easy way to do the following  
short of adding to\_i method to TrueClass/FalseClass.

Here is a dilemma:  
I have a boolean field in my rails app - that is obviously stored as  
Tinyint in mysql. However - I need to generate xml based of the data in  
mysql and send it to customer - there SOAP service requires the field  
in question to have 0 or 1 as the value of this field. So at the time of  
the xml generation I need to convert my False to 0 and my True to 1 (  
which is how they are stored in the DB). Since True & False lack to\_i  
method I could write some if statement that generate either 1 or 0  
depending on true/false state. However I have about 10 of these  
indicators and creating and if/else for each is not very DRY. So what  
you recommend I do?

Or I could add a to\_i method to the True / False class. But I’m not  
sure where should I scope it in my rails app? Just inside this  
particular model or somewhere else?

---

<div class="post-metadata">

**Author:** ![paerez](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/5fc32e/32.png) [@paerez](https://www.ruby-forum.com/u/paerez)\
**Post date:** [March 26, 2010, 5:31pm UTC](https://www.ruby-forum.com/t/converting-trueclass-falseclass-to-integer/185816/2 "2010-03-26T17:31:45Z")

</div>

Hi Nick,

That’s a good question 🙂  
I think a DRY way could be doing it like this:

module BooleanToInteger  
def to\_i  
self ? 1 : 0  
end  
end

[TrueClass, FalseClass].each { |c| c.send :include, BooleanToInteger }

Hope this helps.

/Lasse

2010/3/26 nick ger [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
