While I've used VIM in the past to modify text files in *nix, it's always been a forced affair, with me using it as little as possible to get things done. I've decided to dive into VIM, and try it out as a replacement for my standard code editor, TextMate. After all, I don't need much, just easy text editing, and syntax highlighting. So far, I dig it. Of course it helps that you can install VIM on practically anything (if isn't already there).
It seems like my MUD skills are finally useful.
No one needs to read this site. Publishing this content is meant to force me to research new things, thus helping me to grow as a developer. If you think the things I post about are cool, then well... cool. If not, no big deal.
Tuesday, October 23, 2012
Monday, January 30, 2012
Learning about closures in ruby
Per Wikipedia, a closure is defined as: "In computer science, a closure (also lexical closure, function closure, function value or functional value) is afunction together with a referencing environment for the non-local variables of that function.[1] A closure allows a function to access variables outside its typical scope."
Taken on just its pure definition, it's a little difficult to conceptualize, especially for someone like me who comes from a mostly iterative programming background. So let's look at some sample code (I modified some sample code about Ruby from Wikipedia)
This outputs:
Each proc here is a closure, because the scope of each proc is bound to the scope of where it was defined. In this case, all of the procs are bound to the scope of the create_closure function.
So you can see that even though the execution of create_closure is finished, each proc still has access to the same local closure_value variable that was defined within create_closure function.
Taken on just its pure definition, it's a little difficult to conceptualize, especially for someone like me who comes from a mostly iterative programming background. So let's look at some sample code (I modified some sample code about Ruby from Wikipedia)
puts "learning about closures"
def create_closure(initial_value = 0)
closure_value = initial_value
return Proc.new do |x|
closure_value = x
end, Proc.new do
closure_value += 1
end, Proc.new do
closure_value
end
end
one, two, three = create_closure
myval = 21
puts "one.call(myval) == #{one.call(myval)}"
puts "two.call == #{two.call}"
puts "two.call == #{two.call}"
puts "three.call == #{three.call}"
This outputs:
learning about closures
one.call(myval) == 21
two.call == 22
two.call == 23
three.call == 23
Each proc here is a closure, because the scope of each proc is bound to the scope of where it was defined. In this case, all of the procs are bound to the scope of the create_closure function.
So you can see that even though the execution of create_closure is finished, each proc still has access to the same local closure_value variable that was defined within create_closure function.
Subscribe to:
Posts (Atom)