ruby 整数到布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3534709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ruby integer to boolean
提问by Rafael
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:
我有一个整数类型的 DB 字段,值始终为 0 或 1。如何在 ruby 中获取等效的布尔值?这样当我执行以下操作时,复选框会被适当设置:
<%= check_box_tag 'resend', @system_config.resend %>
回答by Jarrett Meyer
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.
你可以用这个zero?方法。如果为 0,则返回 true。如果您需要向后,您可以轻松地将其否定为!@system_config.resend.zero?。或者您可以扩展 Fixnum 类,添加一个to_b?方法,因为在动态语言中一切都是开放和可扩展的。
class Integer
def to_b?
!self.zero?
end
end


Ruby API: http://ruby-doc.org/core/classes/Fixnum.html#M001050
Ruby API:http: //ruby-doc.org/core/classes/Fixnum.html#M001050
回答by Chuck
1 is your only truth value here. So you can get the boolean truth value with number == 1.
1 是这里唯一的真值。因此,您可以使用number == 1.
回答by gspoosi
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.
这适用于表单、数据库和不了解 ruby 的人。我发现它对 Rails 尤其有用,因为参数通常作为字符串传递/解释,我不想担心这一点。

