Skip to content

Instantly share code, notes, and snippets.

@morganp
Created May 21, 2012 10:38
Show Gist options
  • Save morganp/2761760 to your computer and use it in GitHub Desktop.
Save morganp/2761760 to your computer and use it in GitHub Desktop.
String Integer to Boolean

Jeff Gardner, Catch all

class String
  def to_bool
    return true if self == true || self =~ (/(true|t|yes|y|1)$/i)
    return false if self == false || self.blank? || self =~ (/(false|f|no|n|0)$/i)
    raise ArgumentError.new("invalid value for Boolean: \"#{self}\"")
  end
end

Chuck on stackoverflow

def to_b(i)
  i.to_i == 1
end
@morganp
Copy link
Author

morganp commented May 21, 2012

Check all the same (binary string)

def all_the_same( bin_string )
  word = bin_string.split('')
  #word.map!{|i| i.to_i == 1}
  all_one = word.all?{|x| x == '1' }
  all_zero = word.all?{|x| x == '0' }
  return  (all_one || all_zero)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment