Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String "true" and "false" to boolean

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...?

like image 674
davidb Avatar asked Nov 14 '11 10:11

davidb


People also ask

How do you change a string from true to boolean true?

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".

Is string true a boolean?

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.

How do you convert string false to boolean in TypeScript?

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.


1 Answers

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 
like image 76
cvshepherd Avatar answered Sep 21 '22 12:09

cvshepherd