Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Ruby convert string to bool

Posted on August 24, 2023August 24, 2023 by admin

Overview

In the Ruby language, strings “true” and “false” are interpreted as true when used in the if condition. See example below

if "false"
   puts "yes"
end

Output

"yes"

“false” evaluates to true

Therefore it becomes important to handle string “false” or string “true” correctly.

We can create a custom method that can return boolean true or false based on the content of the string

def true?(str)
  str.to_s.downcase == "true"
end

We can try out the above function

true?("false")
 => false
true?("true")
 => true

Also, note that for strings other than “false” it will give true in return, but the function could be easily modified to handle that case

Note: Check out our system design tutorial series System Design Questions

©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme