字符串"true";和“假"布尔值 [英] String "true" and "false" to boolean

查看:160
本文介绍了字符串"true";和“假"布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails应用程序,并且正在使用jQuery在后台查询我的搜索视图.有字段q(搜索词),start_dateend_dateinternal. internal字段是一个复选框,我正在使用is(:checked)方法来构建要查询的网址:

I have a Rails application and I'm using jQuery to query my search view in the background. There are fields q (search term), start_date, end_date and internal. The internal field is a checkbox and I'm using the is(:checked) method to build the url that is queried:

$.getScript(document.URL + "?q=" + $("#search_q").val() + "&start_date=" + $("#search_start_date").val() + "&end_date=" + $("#search_end_date").val() + "&internal=" + $("#search_internal").is(':checked'));

现在我的问题出在params[:internal]中,因为有一个包含"true"或"false"的字符串,我需要将其强制转换为布尔值.我当然可以这样:

Now my problem is in params[:internal] because there is a string either containing "true" or "false" and I need to cast it to boolean. Of course I can do it like this:

def to_boolean(str)
     return true if str=="true"
     return false if str=="false"
     return nil
end

但是我认为必须有一种更Ruby的方式来解决这个问题!不是吗??

But I think there must be a more Ruby'ish way to deal with this problem! Isn't there...?

推荐答案

据我所知,没有将字符串强制转换为布尔值的内置方法, 但是如果您的字符串仅包含'true''false',则可以将方法缩短为以下内容:

As far as i know there is no built in way of casting strings to booleans, but if your strings only consist of 'true' and 'false' you could shorten your method to the following:

def to_boolean(str)
  str == 'true'
end

这篇关于字符串"true";和“假"布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆