Guest User

Untitled

a guest
Aug 15th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. What is the best way to over-ride methods in an instance?
  2. class DataWrapper
  3. attr_reader :foo, :bar
  4. end
  5.  
  6. case :xml
  7. @data1.to_xml.foo #foo = 4
  8. case :web_table
  9. @data1.to_web_table.foo #foo = "four"
  10.  
  11. array.each{ |o| o.extend(MyModule) }
  12.  
  13. Nib = Struct.new :val do
  14. def to_s
  15. value # Must be implemented by instance/subclass
  16. end
  17. end
  18.  
  19. module Nib::Precise
  20. def value; "%.1f" % val; end
  21. end
  22.  
  23. module Nib::Rough
  24. def value; val.round.to_s; end
  25. end
  26.  
  27. module Nib::Ballpark
  28. def value; ((val/10).round * 10).to_s; end
  29. end
  30.  
  31. nibs = [ Nib.new(33.7), Nib.new(29.1) ]
  32.  
  33. nibs.each{ |n| n.extend(Nib::Precise) }
  34. p nibs.join(", ") #=> "33.7, 29.1"
  35.  
  36. nibs.each{ |n| n.extend(Nib::Rough) }
  37. p nibs.join(", ") #=> "34, 29"
  38.  
  39. nibs.each{ |n| n.extend(Nib::Ballpark) }
  40. p nibs.join(", ") #=> "30, 30"
  41.  
  42. case :xml
  43. @data1.foo.to_xml #foo = 4
  44. case :web_table
  45. @data1.foo.to_web_table #foo = "four"
  46. ....
Add Comment
Please, Sign In to add comment