Guest User

Untitled

a guest
Jul 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. # Here are three ways of running a proc with "local variables" set.
  2. # Really they aren't local variables but functions, it seems it is
  3. # impossible to set local variables or run procs with bindings which
  4. # have the variables set. Trust me I've tried.
  5.  
  6.  
  7. # METHOD 1: WITH A CLASS
  8. # ----------------------
  9. # Create a class then set methods for each arg, then run the proc in
  10. # the newly created class.
  11. #
  12. def in_class(args, proc)
  13. k = Class.new
  14.  
  15. args.each do |a,v|
  16. k.send(:define_method, a) { v }
  17. end
  18.  
  19. k.new.instance_exec &proc
  20. end
  21.  
  22. # METHOD 2: USING METHOD MISSING
  23. # ------------------------------
  24. # Only create one class, which is then stored in a @var, this then
  25. # takes the arguments and uses method missing to pass the correct
  26. # value from the hash.
  27. #
  28. def in_missing_class(a, f)
  29. if @k
  30. if f.arity > 0
  31. @k.new(a).instance_exec(a, &f)
  32. else
  33. @k.new(a).instance_exec(&f)
  34. end
  35. else
  36. @k = Class.new {
  37. def initialize(args)
  38. @a = args
  39. end
  40.  
  41. def method_missing(sym, *args)
  42. if @a.has_key?(sym)
  43. @a[sym]
  44. else
  45. super
  46. end
  47. end
  48. }
  49. in_missing_class(a, f)
  50. end
  51. end
  52.  
  53. # METHOD 3: USING METHOD MISSING AGAIN
  54. # ------------------------------------
  55. # This time create a single instance of a class which has a method
  56. # allowing you to set the hash of args each time it is called, this
  57. # way you aren't creating lots of different instances of a class.
  58. #
  59. def in_missing_object(a, f)
  60. if @o
  61. @o._run a, f
  62. else
  63. @o = Class.new {
  64. def _run(a, f)
  65. @a = a
  66. if f.arity > 0
  67. instance_exec(a, &f)
  68. else
  69. instance_exec &f
  70. end
  71. end
  72.  
  73. def method_missing(sym, *args)
  74. if @a.has_key?(sym)
  75. @a[sym]
  76. else
  77. super
  78. end
  79. end
  80. }.new
  81. end
  82. end
  83.  
  84. a = {:name => "world"}
  85. f = proc { puts "Hello, #{name}!" }
  86.  
  87. in_class(a, f)
  88. #=> Hello, world!
  89. in_missing_class(a, f)
  90. #=> Hello, world!
  91. in_missing_object(a, f)
  92. #=> Hello, world!
Add Comment
Please, Sign In to add comment