字符串“真"和“假"到布尔值
我有一个 Rails 应用程序,我正在使用 jQuery 在后台查询我的搜索视图.有字段 q
(搜索词)、start_date
、end_date
和 internal
.internal
字段是一个复选框,我使用 is(:checked)
方法来构建被查询的 url:
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