Created
February 28, 2010 13:28
-
-
Save rklemme/317580 to your computer and use it in GitHub Desktop.
Example code of blog article "Code Massage"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! ruby19 | |
ADDR = %r{[-.\w]+@[-.\w]+} | |
email = DATA.read.freeze | |
# 1. Java style | |
subst = {} | |
puts email.gsub(ADDR) {|match| | |
if subst.has_key? match | |
subst[match] | |
else | |
subst[match] = "<<MAIL #{subst.size}>>" | |
end | |
} | |
# 2. a little more sophisticated | |
subst = {} | |
puts email.gsub(ADDR) {|match| | |
subst.fetch(match) {|k| subst[k] = "<<MAIL #{subst.size}>>" } | |
} | |
# 3. o||=erator | |
subst = {} | |
puts email.gsub(ADDR) {|match| | |
subst[match] ||= "<<MAIL #{subst.size}>>" | |
} | |
# 4. outsourcing | |
subst = Hash.new {|h,k| h[k] = "<<MAIL #{h.size}>>"} | |
puts email.gsub(ADDR) {|match| subst[match]} | |
# 5. getting tricky | |
subst = Hash.new {|h,k| h[k] = "<<MAIL #{h.size}>>"} | |
puts email.gsub(ADDR, &subst.method(:[])) | |
# 6. even shorter with a general solution | |
class Object | |
def to_proc(m = :[]) | |
method(m).to_proc | |
end | |
end | |
subst = Hash.new {|h,k| h[k] = "<<MAIL #{h.size}>>"} | |
puts email.gsub(ADDR, &subst) | |
# 7. golf | |
puts email.gsub(ADDR, &Hash.new {|h,k| h[k] = "<<MAIL #{h.size}>>"}) | |
# 8. the fun begins | |
Name = Struct.new :forename, :surname | |
# unfortunately this does not work with the default Struct.[] | |
def Name.[](a) | |
new(*a) | |
end | |
p [ | |
["John", "Doe"], | |
["John", "Cleese"], | |
["Mickey", "Mouse"], | |
].map(&Name) | |
def Name.create(a) | |
new(*a) | |
end | |
p [ | |
["John", "Doe"], | |
["John", "Cleese"], | |
["Mickey", "Mouse"], | |
].map(&Name.to_proc(:create)) | |
__END__ | |
From some-user@his.domain.com | |
To: whatever@somewhere.else | |
Cc: foo@bar.com, some-user@his.domain.com | |
Subject: I thought you should know | |
Hi, | |
id you know that foo@bar.com recently sent me an email | |
at my address some-user@his.domain.com? | |
Cheers | |
-- | |
mailto:some-user@his.domain.com | |
EOM |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment