Skip to content

Instantly share code, notes, and snippets.

@robcthegeek
Created January 21, 2012 23:41
Show Gist options
  • Save robcthegeek/1654531 to your computer and use it in GitHub Desktop.
Save robcthegeek/1654531 to your computer and use it in GitHub Desktop.
Ruby Open Classes - Code Examples
class String
# taken from: http://regexlib.com/REDetails.aspx?regexp_id=2558 - (escaped the forward-slashes as well)
def is_email?
self =~ /^((([!#$\%&'*+\-\/=?^_`{|}~\w])|([!#$\%&'*+\-\/=?^_`{|}~\w][!#$\%&'*+\-\/=?^_`{|}~\.\w]{0,}[!#$\%&'*+\-\/=?^_`{|}~\w]))[@]\w+([-.]\w+)*\.\w+([-.]\w+)*)$/
end
def isnt_email?
!is_email?
end
end
puts "See this is an email!" if "[email protected]".is_email?
puts "And so is this" if "[email protected]".is_email?
puts "but I'm not!" if "fail".isnt_email?
# pretend this is in an OSS library..
class PrinterError
attr_reader :code
def initialize(code)
@code = code
end
end
# So at this point the code is defined elsewhere, let's open it up to add our messages.
class PrinterError
def message
@code == 42 ? "PC LOAD ERROR" : "Unexpected error printing document"
end
end
puts PrinterError.new(100).message
puts PrinterError.new(42).message
# using a completey normal string method..
puts "oh hai!".upcase
# along comes a naughty developer
class String
def upcase
"#{self}\nCATS: ALL YOUR BASE ARE BELONG TO US."
end
end
# now what happens when we call the same code as before??
puts "oh hai!".upcase

From blog post here.

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