Last active
December 19, 2015 11:09
-
-
Save Jacke/5945362 to your computer and use it in GitHub Desktop.
Magic with &:symbol and &block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Translator | |
| def speak &language # Proc.new { |obj| obj.send(:method) } | |
| language.call(self) # self make obj so it convert to self.send(:method) | |
| # Proc.new { |obj| obj.send(method) } .call(self) | |
| end | |
| protected | |
| def french | |
| 'bon jour' | |
| end | |
| def spanish | |
| 'hola' | |
| end | |
| def turkey | |
| 'gobble' | |
| end | |
| def method_missing *args | |
| 'awkward silence' | |
| end | |
| end | |
| irb(main):002:0> translator = Translator.new | |
| => # | |
| irb(main):003:0> translator.speak(&:spanish) | |
| => «hola» | |
| irb(main):004:0> translator.speak(&:turkey) | |
| => «gobble» | |
| irb(main):005:0> translator.speak(&:italian) | |
| => «awkward silence» |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Symbol | |
| def to_proc | |
| Proc.new { |*args| args.shift.__send__(self, *args) } | |
| end | |
| end | |
| class Symbol | |
| def to_proc | |
| Proc.new { |obj| obj.send self } | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment