Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! 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
Add Comment
Please, Sign In to add comment