From: Logan Capaldo Date: 2007-09-09T00:16:25+09:00 Subject: Re: #to_b - why isn't this one already in there? On 9/7/07, Giles Bowkett wrote: > everybody knows > > if "false" > > returns true. there are situations where that's a pain. I did a Rails > thing where I was creating objects and calling methods from options > hashes which I sometimes got by simply passing in params from a > controller and sometimes actually wrote as code. so I would have > > @some_boolean = options[:some_boolean] > > and five minutes later I'd be stubbing my metaphorical toe on an > > if "false" > > statement. > > so I changed it to this: > > @some_boolean = options[:some_boolean].to_b > > and implemented #to_b by doing this: > > class String > def to_b > case self > when "true" > true > when "false" > false > else > raise Exception > end > end > at that point I could pass in options hashes and it didn't matter > whether they came in properly and correctly as actual boolean values > or blustered in the servants' entrance as URL parameters. > This proposal, and the responses (the negative ones) I find interesting, because I think it highlights a "problem" with most of the #to_blah methods, especially on String. If you can accept "32".to_i == 32 or "1.0".to_f == 1.0 (pretend for a moment theres no such thing as floating point inaccuracy ;) ) then it seems perfectly reasonable to accept "true".to_b == true. I think what's throwing people is that string doesn't need an additional method to be used in a boolean context, and they find the (if I may use the word) "cast" distasteful. the #to_blah methods aren't "cast"s they are conversions and so from that point of view I see nothing wrong with #to_b. On the other hand, I think your implementation is flawed. #to_blah methods don't raise exceptions if they can give you some value. E.g.: "google".to_i #=> 0. It doesn't raise an exception. So I would pick one of (true, false) to be the result of "gooble".to_b.