If an instance variable belongs to a class, can I access the instance variable (e.g. @hello) directly using the class instance?
class Hello
def method1
@hello = "pavan"
end
end
h = Hello.new
puts h.method1
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.
Yes, you can use
instance_variable_getlike this:If the variable is undefined (first call of
instance_variable_getin my example) you getnil.As Andrew mention in his comment:
A better way is to define an accessor:
If you want another method name, you could alias the accessor:
alias :my_hello :hello.And if the class is not defined in your code, but in a gem: You can modify classes in your code and insert new functions to classes.