I am new to ruby and rails and sometimes I still get confused between these two. I have tried to call an instance variable by adding a name of the instance variable after an object(john.name), and I hope that the result would be John. Unfortunately NoMethodError appears. So I searched for an answer and found out that you can use instance_variable_get method to do this. However, I believe that it is possible to do this in RAILS when you want to access the instance variable of an object in VIEWS.
class Person
def initialize(name)
@name = name
end
end
john = Person.new("John")
puts john.instance_variable_get(:@name)
=> John
puts john.name
=> NoMethodError
attr_accessor. Below two answers show you how.class C; def initialize; @x = 1; end; end; C.new.instance_variable_get(:@x) #=> 1.