I haven't learned any functional programming languages yet, so I don't fully understand your code, but I think that this is the way Ruby does all the time. Ruby calls such constructions blocks. For example, instead of a for loop, Rubyists would write
Code:
some_iterable_object.each do |item|
# This is the body of a block, which is executed in the
# scope in which it's defined, not the scope of the
# each method.
end
It also enables cool stuff like auto-closing files:
Code:
File.open('some/file') do |file|
file.each_line do |line|
puts line
end
end
No need to explicitly close the file. I'm not sure how File.open is implemented, but this is equivalent (sans error checking):
Code:
class File
def File.open(*args, &block)
file = File.new *args
begin
yield file # file is passed to the block as an argument, and the block is executed in the scope in which it was defined; not this scope
ensure
file.close
end
end
end
EDIT: I should add that blocks are one of my favorite Ruby features.