字符串"true";和“假"布尔值
我有一个Rails应用程序,并且正在使用jQuery在后台查询我的搜索视图.有字段q
(搜索词),start_date
,end_date
和internal
. 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