class MainController < ApplicationController
@my_var = 123
def index
var1 = @my_var
end
def index2
var2 = @my_var
end
end
Why is neither var1 no var2 equal to 123?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Variables with
@are instance variables in ruby. If you’re looking for class variables, they’re prefixed with@@, so you should be using@@my_var = 123instead.And the reason you can’t use instance variables that way, is because if you define instance variables outside methods, they don’t live in the same scope as your methods, but only live while your class is interpreted.
var1in your example is a local variable, which will only be visible inside theindexmethod.Examples: