Skip to content

Instantly share code, notes, and snippets.

@roryokane
Created August 1, 2012 18:32
Show Gist options
  • Save roryokane/3229581 to your computer and use it in GitHub Desktop.
Save roryokane/3229581 to your computer and use it in GitHub Desktop.
Object#apply_repeatedly and #send_repeatedly for Ruby
# 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
# 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