Information Technology Reference
In-Depth Information
In Ruby, a variable is accessible within the outermost scope of its declaration. Consider the
following example that better demonstrates variable scope. First, a top-level variable named
bacon_type
is declared and assigned the value
crispy
. Next, the bacon is cooked twice and
an additional variable named
temperature
is assigned the value
300
. Finally, the script at-
tempts to access the
temperature
variable, which is now out of scope:
bacon_type
=
'crispy'
2
.
times
ddo
puts
bacon_type
temperature
=
300
end
end
puts
temperature
The
bacon_type
variable is declared at the top-level scope, so it will be accessible every-
where within this context.
We can access the
bacon_type
variable inside a more specific scope, such as a loop.
A
variable declared inside a scope is accessible only from inside that scope.
Ou
tside of the scope of declaration, attempting to access a variable will result in an ex-
ception (
undefined local variable or method 'temperature'
).
WAIT… WHAT ARE YOU SAYING?
It's worth noting that if you're feeling a bit lost at this point, this topic presumes a basic
level of experience with object-oriented programming concepts. If you're not clear about
variables, scope, and loops, you'll probably want to brush up on some of the basics of
object-oriented programming and then head back here to get up to speed on Ruby and
Chef. A great topic on object-oriented programming with Ruby is
Practical Object-Ori-
ented Design in Ruby
, by Sandi Metz.