Posted By

Shamaoke on 12/29/10


Tagged

method ruby block


Versions (?)

Call a block or a method


 / Published in: Ruby
 

Call a block if it's given otherwise call a method.

  1. # encoding: utf-8
  2.  
  3. class Parent
  4. def one
  5. 'ok!'
  6. end
  7. end
  8.  
  9. class Child < Parent
  10. def initialize(&block)
  11. @do = block || method(:one)
  12. end
  13.  
  14. def do
  15. @do.call
  16. end
  17. end
  18.  
  19. child_one = Child.new
  20. child_two = Child.new { 'ok two!' }
  21.  
  22. puts [
  23. child_one.do, #=> ok!
  24. child_two.do #=> ok two!
  25. ]

Report this snippet  

You need to login to post a comment.