Here’s what I’d like to do:
class Directory
def doSomething
end
def subs
# => an array of Directory objects
end
def recursively (method)
self.subs.each do |sub|
sub.method
sub.recursively method
end
end
end
cd = Directory.new
cd.recursively 'doSomething'
# ...and extra points if theres a way to:
cd.recursively.doSomething
To put this into perspective I’m creating a small script that will make changes to files in a Directory as well as all its sub-directories. These sub-directories will just be extended Directory objects.
So is there a way to pass a method as a parameter of another method?
You could use
Object#send, wheremethodis a string or symbol representing the method name, as in your first example. Just change your#recursivelyto this:UPDATE
For your “extra points” question, and picking up on megas’ answer, here’s a stab at an Enumerator-based approach. Drop this into your Directory:
And call it like this: