Ruby Variable

wang xiao bo 's photo
wang xiao bo

Published on Sep 1, 2021

1 min read

Subscribe to my newsletter and never miss my upcoming articles

// Variable Scope
array = [1,2,3,4,5]

array.each do |item|
  array2 = []
  array2.push(item * 2)
end

puts array2 //undefined method `array2' for main
// Variable Assignment is not Working
1 = "Hello world"

If we run the above code, we will get an error. Why?

We are getting an error because the variable array2 is declared inside the do end block.

A variable that is born inside a do end block is not visible outside of the do end block.

It means a variable has a scope. If we try to access a variable outside of its scope, then we will get an error.

If a variable is born inside a do end block, then that variable’s scope is limited to that do end block. Outside of that do end block, no one knows about that variable. So how do we fix the previous error? We need to take variable array2 outside of the do end block as shown below

bo = "Hello world"
puts bo

_hello = "Hello world"
puts _hello
 
Share this