Call a block or a method


/ Published in: Ruby
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.