Learning about Ruby blocks here. What is the point of having block local variable in this example:
When you can just do the below instead? The x
in the block is already going to have its own scope, which is different than the x
that is outside the block.
Show activity on this post. My understanding was that ruby blocks have block scope, and all variables created inside block will live only within the block. If you take the food variable inside the block (Each block), my understanding was that it has block scope.
Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.
Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
Block scopes nest inside their lexically enclosing scope:
foo = :outerfoo
bar = :outerbar
1.times do |;bar|
foo = :innerfoo
bar = :innerbar
baz = :innerbaz
end
foo #=> :innerfoo
bar #=> :outerbar
baz # NameError
You need a way to tell Ruby: "I don't want this variable from the outer scope, I want a fresh one." That's what block local variables do.
The point they're trying to make is that a block local variable (or a block parameter) will be completely separate from the variable outside of the block even if they have the same name, but if you just refer to x
within the block without it being a block local variable or a block parameter, you're referring to the same x
that exists outside the block.
They have this example right above the one you cite:
x = 10
5.times do |y|
x = y
puts "x inside the block: #{x}"
end
puts "x outside the block: #{x}"
Output:
x inside the block: 0
x inside the block: 1
x inside the block: 2
x inside the block: 3
x inside the block: 4
x outside the block: 4
Note that this is only the case if you refer to x
before the block. If you removed the x = 10
line at the beginning, then the x
in the block would be completely local to the block and that last line would error out (unless you had a method named x
in the same object, in which case it would call that method).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With