We can use Ruby to convert a string to boolean with the help of the empty? method. We first need to determine if the string is empty or non-empty. Non-empty strings will be converted to true and empty strings will be converted to false.
some_string = "This is a string"
empty_string = ""
some_string = !some_string.empty?
empty_string = !empty_string.empty?
puts some_string
puts empty_string
#Output:
true
false
We can put this code in a method we create called convert_string_to_bool, so that all we have to do is run this method on a string to convert it to a boolean.
def convert_string_to_bool(str)
return !str.empty?
end
And now let’s run an example with this method to see that it works.
def convert_string_to_bool(str)
return !str.empty?
end
puts convert_string_to_bool("This is a string")
puts convert_string_to_bool("")
#Output
true
false
If we just want to check if a string is equal to “true”, then we can perform a check with the equality operator ==.
true_string = "true"
print true_string == "true"
#Output:
true
When working with different object types in Ruby, the ability to convert objects to other object types easily is valuable. One such case is if you want to convert a string to a boolean. To convert a string object to a boolean object in Ruby, we can use the Ruby empty? method.
The empty? method will return true if a string is empty, and false if it is not empty. So we just have to set the value of our string to the opposite of what the empty?
method returns.
Below is our method again to help convert strings to boolean objects in Ruby.
def convert_string_to_bool(str)
return !str.empty?
end
non_empty_string = "This is a string"
empty_string = ""
non_empty_string = convert_string_to_bool(non_empty_string)
empty_string = convert_string_to_bool(empty_string)
puts non_empty_string
puts empty_string
#Output
true
false
Checking if String is Equal to true in Ruby
If we just want to check if a string is equal to “true”, then we can perform a check with the equality operator ==. This can be the case if we have user input and want to see if the user input is “true” or “false”.
As we know from above, a string with the value “true” will resolve to true when converted to a boolean value. Therefore, we just need to do a simple check to verify the value of the string object. Below is a simple example showing you how to check if a string is equal to “true” in Ruby.
true_string = "true"
print true_string == "true"
#Output:
true
Hopefully this article has been useful for you to learn how to use Ruby to convert a string to a boolean.