Class: String

Inherits:
Object show all
Defined in:
lib/tfg/support/core_ext/string/to_boolean.rb

Instance Method Summary collapse

Instance Method Details

#to_booleanObject

Attempts to cast the string to true or false. This is done by comparison with known truthy and falsey values.

"Yes".to_boolean #=> true
"1".to_boolean #=> true

"NO".to_boolean #=> false
"FaLsE".to_boolean #=> false

Raises:

  • ArgumentError when the string does not match either a truthey or falsey value.



15
16
17
18
19
20
# File 'lib/tfg/support/core_ext/string/to_boolean.rb', line 15

def to_boolean
  return true if self =~ (/\A(true|t|yes|y|1)\Z/i)
  return false if self =~ (/\A(false|f|no|n|0)\Z/i)

  raise ArgumentError.new("String \"#{self}\" cannot be cast to boolean.")
end