Ruby Tip of The Day – Variable Scope
I was writing a few scripts today and noticed that I kept getting "undefined local variable or method" as an error.
Coming from PHP I am use to writing a variable globally in a page/script and then being able to access that variable inside a function on the same page. Though it's not proper coding practice, I did not want my closures to have 20 parameters, but rather have a few parameters in my function then take the rest as configuration parameters inside the script.
Here is some code that breaks:
foo = 123def a puts fooenda
Here is some code that works:
$foo = 123def a puts $fooenda
There are some other variable scopes as well, instance scope with an @ before the variable name, and local variables have no prefix.
It's funny, to get Ruby to work like PHP, I had to make it look like PHP.
Comments
No comments yet.
Leave a comment