I have a DB field that is integer type and values are always 0 or 1. How do I grab the equivalent boolean value in ruby? such that when i do the following the check box is set appropriately:
<%= check_box_tag 'resend', @system_config.resend %>
You could use the zero? method. It returns true if 0. If you need to backwards, you could easily negate it to !@system_config.resend.zero?. Or you could extend the Fixnum class, adding a to_b? method, since everything is open and extensible in dynamic languages.
class Integer
def to_b?
!self.zero?
end
end

Ruby API: http://ruby-doc.org/core/classes/Fixnum.html#M001050
nonzero? which may read better than !zero?.nonzero? function is, but would have no idea what to_b? is!nonzero? - it returns truthy and falsy values, but not true as zero? does (they are defined in different classes, see ruby-doc.org/core-1.9.3/Fixnum.html#method-i-zero-3F versus ruby-doc.org/core-1.9.3/Numeric.html#method-i-nonzero-3Fnonzero? did not return a boolean as most ruby predicate methods do and came upon this ticket debating getting this corrected bugs.ruby-lang.org/issues/9123. Seems not everyone agrees this is an issue so it unfortunately doesn't seem to be going anywhere.1 is your only truth value here. So you can get the boolean truth value with number == 1.
== and zero? methods are standard Ruby. But it so happens that number == 1 reads more clearly than !number.zero? IMO.I had the same problem and dealt with it this way:
def to_boolean(var)
case var
when true, 'true', 1, '1'
return true
when false, 'false', 0, '0'
return false
end
end
This works with forms, databases and people who don't know Ruby. I found it to be useful especially with Rails, since parameters are often passed/interpreted as strings and I don't want to worry about that.