0

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
4
  • You can't access instance variable directly. Variables are generally part of something, confined within a method or class, say. But to get its value, you have it set it to a method or use attr_accessor. Below two answers show you how. Commented Mar 12, 2017 at 13:07
  • Ruby is simple. All an object exposes are methods. You can't access instance variables from outside directly. Commented Mar 12, 2017 at 13:20
  • @arjun, You don't need an accessor: class C; def initialize; @x = 1; end; end; C.new.instance_variable_get(:@x) #=> 1. Commented Mar 12, 2017 at 20:37
  • Assuming that the variable appears once in the code. But generally variables are modified many times and I believe, that the proper way is to define it in a class method and call that instead. Commented Mar 12, 2017 at 20:41

2 Answers 2

2

Use attr_reader to read the value of an instance variable

class Person
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

john = Person.new("John")
john.name #=> "John"

attr_reader adds a getter method to the class, in this case

def name
  @name
end

Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

1

You need to define the method to access your instance variable.

class Person
  def initialize(name)
    @name = name
  end

  def name
    @name
  end
end

Or you can simply add attr_accessor which will set getter and setter methods

class Person
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

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.