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

Hi,

is there a ruby / rails builtin function that converts

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

to a boolean?

cheers
peter

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”
end

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
false
and the method should return true / false

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

example:

“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:

cheers
peter


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

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.

_Kevin

That’s pretty neat… :slight_smile:

Thanks!

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.

Julian

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