Convert 0, "0", "true", etc. to boolean


is there a ruby / rails builtin function that converts

  • 0 / 1
  • “0” / “1”
  • “yes” / “no”
  • “true” / “false”

to a boolean?


On Jun 24, 2006, at 11:41, Pete wrote:

is there a ruby / rails builtin function that converts

  • 0 / 1
  • “0” / “1”
  • “yes” / “no”
  • “true” / “false”

to a boolean?

The answer is that they are evaluated as booleans when needed:

if 0
puts “0 is true”

You probably knew that. If for whatever reason you need a mapping
that returns false for 0, “0”, “no”, “false”, you need to write your
own. I guess the question has a valid justification so I won’t warn
against that a priori :-).

– fxn

I would like this functionality to convert some
user input into a boolean value for storing in the model.

The user should be able to input different presentations of true and
and the method should return true / false

I could imagine there is some method deep inside ActiveRecord /
ActionPack / ActionSupport
that does this already…


“yes”, “1”, “t”, “TRUE”, … -> true
“No”, “0”, "000, “f”, “, false”, “FalSe”, … -> false

Xavier N. schrieb:

On Saturday, June 24, 2006, at 11:41 AM, Pete wrote:


Rails mailing list
[email protected]

What do you want it to return if it doesn’t match either true or false?
Keep in mind that ‘false’ and ‘nil’ both are treated as ‘false’ in
conditional tests by Ruby.


That’s pretty neat… :slight_smile:


Julian G. schrieb:

You could use a regular expression like:

myfield.match(/(true|t|yes|y|1)$/i) != nil

This will return true for case insensitive true, t, yes, y and 1 - false
for everything else.


In rails 2, you can use
ActiveRecord::ConnectionAdapters::Column.value_to_boolean(“0”) for
1,0,‘true’,‘false’,‘1’,‘0’, ‘t’, and ‘f’.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs