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'));
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
But I think there must be a more Ruby'ish way to deal with this problem! Isn't there...?
To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
To get boolean true, string must contain "true". Here, case is ignored. So, "true" or "TRUE" will return boolean true. Any other string value except "true" returns boolean false.
To convert a string to a boolean in TypeScript, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With