Guest User

Untitled

a guest
Apr 30th, 2018
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. #! ruby19
  2.  
  3. ADDR = %r{[-.\w]+@[-.\w]+}
  4. email = DATA.read.freeze
  5.  
  6. # 1. Java style
  7.  
  8. subst = {}
  9.  
  10. puts email.gsub(ADDR) {|match|
  11. if subst.has_key? match
  12. subst[match]
  13. else
  14. subst[match] = "<<MAIL #{subst.size}>>"
  15. end
  16. }
  17.  
  18. # 2. a little more sophisticated
  19.  
  20. subst = {}
  21.  
  22. puts email.gsub(ADDR) {|match|
  23. subst.fetch(match) {|k| subst[k] = "<<MAIL #{subst.size}>>" }
  24. }
  25.  
  26. # 3. o||=erator
  27.  
  28. subst = {}
  29.  
  30. puts email.gsub(ADDR) {|match|
  31. subst[match] ||= "<<MAIL #{subst.size}>>"
  32. }
  33.  
  34. # 4. outsourcing
  35.  
  36. subst = Hash.new {|h,k| h[k] = "<<MAIL #{h.size}>>"}
  37.  
  38. puts email.gsub(ADDR) {|match| subst[match]}
  39.  
  40. # 5. getting tricky
  41.  
  42. subst = Hash.new {|h,k| h[k] = "<<MAIL #{h.size}>>"}
  43.  
  44. puts email.gsub(ADDR, &subst.method(:[]))
  45.  
  46. # 6. even shorter with a general solution
  47.  
  48. class Object
  49. def to_proc(m = :[])
  50. method(m).to_proc
  51. end
  52. end
  53.  
  54. subst = Hash.new {|h,k| h[k] = "<<MAIL #{h.size}>>"}
  55.  
  56. puts email.gsub(ADDR, &subst)
  57.  
  58. # 7. golf
  59.  
  60. puts email.gsub(ADDR, &Hash.new {|h,k| h[k] = "<<MAIL #{h.size}>>"})
  61.  
  62. # 8. the fun begins
  63.  
  64. Name = Struct.new :forename, :surname
  65.  
  66. # unfortunately this does not work with the default Struct.[]
  67. def Name.[](a)
  68. new(*a)
  69. end
  70.  
  71. p [
  72. ["John", "Doe"],
  73. ["John", "Cleese"],
  74. ["Mickey", "Mouse"],
  75. ].map(&Name)
  76.  
  77. def Name.create(a)
  78. new(*a)
  79. end
  80.  
  81. p [
  82. ["John", "Doe"],
  83. ["John", "Cleese"],
  84. ["Mickey", "Mouse"],
  85. ].map(&Name.to_proc(:create))
  86.  
  87. __END__
  88. From some-user@his.domain.com
  89. To: whatever@somewhere.else
  90. Cc: foo@bar.com, some-user@his.domain.com
  91. Subject: I thought you should know
  92.  
  93. Hi,
  94.  
  95. id you know that foo@bar.com recently sent me an email
  96. at my address some-user@his.domain.com?
  97.  
  98. Cheers
  99.  
  100. --
  101. mailto:some-user@his.domain.com
  102. EOM
Add Comment
Please, Sign In to add comment