Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Ruby convert string to bool

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

Table of Contents

  • Overview

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

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2025 Welcome To Golang By Example | Design: Web XP