In Ruby, "false"
(i.e. string false) is not type converted to boolean false
automatically. In fact, it evaluates to true
:
print "false" == true #=> true
This is the correct interpretation because in Ruby, any value other than falsy values will always return true
when evaluated. Since "false"
is a non-empty string, it is by definition truthy.
However, in some cases, such as during data transfer, deserialization, or making HTTP request to the server, you might want to interpret string "false"
as boolean false
. To do so, you can use a conditional expression to convert the string to a boolean value, for example, like so:
def parse_str_false(str) false if str.downcase == "false" end puts parse_str_false("false") #=> false puts parse_str_false("false").class #=> FalseClass puts parse_str_false("true") #=> nil puts parse_str_false("foo") #=> nil # ...
Calling the String#downcase
method on the string is important, especially if the incoming string's case is unknown.
You can also use regular expression to achieve the same, for example, by using basic pattern-matching operator (=~
). However, it would be an overkill if you only check for a single value (i.e. string false). It could prove useful though, if you had a case where false is represented by multiple strings (such as "false"
, "f"
, "no"
, "n"
, "0"
, "off"
, etc.). In that case, you could do something like the following:
def parse_str_false(str) false if str =~ /^(false|f|no|n|off|0)$/i end puts parse_str_false("false") #=> false puts parse_str_false("False") #=> false puts parse_str_false("f") #=> false puts parse_str_false("No") #=> false puts parse_str_false("n") #=> false puts parse_str_false("0") #=> false # ... puts parse_str_false("true") #=> nil puts parse_str_false("foo") #=> nil # ...
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.