-
-
Save stonegao/318146 to your computer and use it in GitHub Desktop.
This file contains hidden or 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(:[]).to_proc) | |
# 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 [email protected] | |
To: [email protected] | |
Cc: [email protected], [email protected] | |
Subject: I thought you should know | |
Hi, | |
id you know that [email protected] recently sent me an email | |
at my address [email protected]? | |
Cheers | |
-- | |
mailto:[email protected] | |
EOM |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment