Boolean to int conversion


(Mehr, Assaph (Assaph)) #1

Ruby is dynamic, and you can always modify existing classes:

irb(main):004:0> class TrueClass
irb(main):005:1> def to_i
irb(main):006:2> 1
irb(main):007:2> end
irb(main):008:1> end
nil
irb(main):009:0> class FalseClass
irb(main):010:1> def to_i
irb(main):011:2> 0
irb(main):012:2> end
irb(main):013:1> end
nil
irb(main):014:0> true.to_i
1
irb(main):015:0> false.to_i
0
irb(main):016:0> (1==1).to_i
1
irb(main):017:0> (1==2).to_i
0

Ruby considers false to be only nil (The singleton instance of NilClass)
and false (the singleton instance of FalseClass). Everything else is
true.
The question remains, why do you need it? What can’t you do the ruby
way?

HTH,
Assaph

···

-----Original Message-----
From: Cere Davis [mailto:cere@u.washington.edu]
Sent: Wednesday, 18 February 2004 14:10 PM
To: ruby-talk ML
Subject: boolean to int conversion

I’m a bit of a Ruby newbie so be kind pls.

Could someone tell me if there’s an easy way to make a value of True go
to 1 and False goto 0?

a sort of to_i method?

Thanks,
Cere