Convert string to Boolean using Regular Expressions

Regular expressions can be employed to match specific patterns in strings, such as “true” or “false”, and then convert them to Boolean values.

Syntax:

!!(string =~ /^(true|t|yes|y)$/i)

Example: In this example we uses a regular expression /^(true|t|yes|y)$/i to match strings like “true”, “t”, “yes”, or “y” regardless of case. The expression !!(string =~ /^(true|t|yes|y)$/i) returns true if the string matches the pattern, otherwise false.

Ruby
def convert_to_boolean_using_regex(string)
  !!(string =~ /^(true|t|yes|y)$/i)
end

# Test examples
string1 = "True"
string2 = "false"
string3 = "Yes"

 
puts "String: #{string1}, Boolean Value: #{convert_to_boolean_using_regex(string1)}"  # Output: true
puts "String: #{string2}, Boolean Value: #{convert_to_boolean_using_regex(string2)}"  # Output: false
puts "String: #{string3}, Boolean Value: #{convert_to_boolean_using_regex(string3)}"  # Output: true

Output
String: True, Boolean Value: true
String: false, Boolean Value: false
String: Yes, Boolean Value: true


How to convert String to Boolean in Ruby?

In this article, we will learn how to convert string to Boolean in Ruby using various methods. Let’s understand each of them with the help of examples.

Table of Content

  • Converting string to Boolean using String#casecmp
  • Converting string to Boolean using String#downcase
  • Convert string to Boolean using Regular Expressions

Similar Reads

Converting string to Boolean using String#casecmp

casecmp method compares two strings while ignoring the case and returns 0 if they are equal, -1 if the receiver precedes the argument, and 1 if the receiver follows the argument alphabetically....

Converting string to Boolean using String#downcase

String#downcase converts the string to lowercase and then we compare it with “true” to check if it represents true.....

Convert string to Boolean using Regular Expressions

Regular expressions can be employed to match specific patterns in strings, such as “true” or “false”, and then convert them to Boolean values....