2

I get an error for the line number 6. I try to print a global variable which the ruby interpreter doesn't recognize. why is that ? How can i modify this ?

localVar = "Local Variable"
$globalVar = "Global Variable"
puts(localVar)
def func
puts("From the function func")
puts(globalVar) #line 6
end

def changer
globalVar = "New Global Var"
puts("New Global Var : #{globalVar}")
end
func #Call the function func
changer #Call the function changer

Output :

Local Variable
From the function func
global.rb:6:in `func': undefined local variable or method `globalVar' for main:Object (NameError)
    from global.rb:13:in `<main>'

3 Answers 3

3

You need to put the $ every time in front of the variable name.

puts($globalVar) #line 6
Sign up to request clarification or add additional context in comments.

Comments

1

You always need to use the $ prefix for global variables in Ruby, when you define or use them.

Comments

1

This shall do the trick for you. $ is part of the variable name.

puts($globalVar) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.