Created
August 1, 2012 18:32
-
-
Save roryokane/3229581 to your computer and use it in GitHub Desktop.
Object#apply_repeatedly and #send_repeatedly for Ruby
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
| # encoding: utf-8 | |
| 3 * 2 * 2 * 2 * 2 #=> 48 | |
| 3 * (2 ** 4) #=> 48 | |
| 3.send_repeatedly(4, :*, 2) #=> 48 | |
| 3.apply_repeatedly(4) { |obj| obj * 2 } #=> 48 | |
| BasicObject.singleton_class.superclass # => Class | |
| BasicObject.singleton_class.superclass.superclass.superclass.superclass #=> BasicObject | |
| BasicObject.singleton_class.send_repeatedly(4, :superclass) #=> BasicObject | |
| BasicObject.singleton_class.apply_repeatedly(4) { |obj| obj.superclass } #=> BasicObject |
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
| # encoding: utf-8 | |
| class Object | |
| def send_repeatedly(repetitions, symbol, *send_args) | |
| apply_repeatedly(repetitions) { |obj| obj.send(symbol, *send_args) } | |
| end | |
| def apply_repeatedly(repetitions) | |
| obj = self | |
| repetitions.times do | |
| obj = yield(obj) | |
| end | |
| obj | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment