From: "aef (Alexander E. Fischer)" Date: 2012-03-22T07:32:44+09:00 Subject: [ruby-core:43547] [ruby-trunk - Feature #6180] to_b for converting objects to a boolean value Issue #6180 has been updated by aef (Alexander E. Fischer). I too would very much like to see a #to_bool method on every object. In my opinion, if you define a public API, you should be as strict as possible about what each method returns, so that your users can rely on it, but also to minimize the possible usage scenarios of the API. The latter one helps me as developer to keep the API working for a maximum amount of users after I changed internal aspects. Because of this I always cast return values of question mark methods into true or false (some languages would call it Boolean for simplicity) with the double ! operator, which I think is ugly because its not so obvious what the operator does at first. I do this because I imagine people using the output in ways that I surely didn't intend nor that I will support after changes. In some cases they could even circumvent my public API. I think that an object should protect its encapsulation so that, if you want to break the encapsulation (circumvent the public API) by force (which is possible most of the times in Ruby), you have to do it knowingly. A small example: object.value = "valid string" object.value? # => "valid string" object.value?.insert(0, "in") object.value? # => "invalid string" This works if the returned object is a String, Array, Hash, Set or any oder mutable object. To prohibit such usage I could use #freeze, which does not protect deep structures perfectly out of the box and may be unhandy for further usage of the returned object or I could #dup or #clone the object before giving it out, which will probably need more processing power than simply returning a boolean casted value, either through !! or #to_bool. ---------------------------------------- Feature #6180: to_b for converting objects to a boolean value https://bugs.ruby-lang.org/issues/6180#change-25026 Author: AaronLasseigne (Aaron Lasseigne) Status: Open Priority: Normal Assignee: Category: Target version: When a boolean return value is required it has become common practice is to use "!!" to convert the object. It would be more consistent to provide a "to_b" method on Object. -- http://bugs.ruby-lang.org/