Yohsuke Inoda Yohsuke Inoda - 17 days ago 7
Ruby Question

How to get private variables of instance object without calling method

Is it possible to call a specific method (or getting instance variables) without instance method from instance object in Ruby?

class Foo
def initialize(arg)
@bar = arg
end
end

f = Foo.new('test')
p f #=> "test" (in this case, get @bar variable without instance method)





For instance, if Example class is defined,

ex = Example.new
ex #=> #<Example:0x00000000000000>


I want to do, like this.

ex = Example.new('hello')
ex #=> "hello"

Answer

You can use inspect for p and to_s for puts

class Foo
  def initialize(arg)
    @bar = arg
  end
  def inspect
    @bar
  end
  def to_s
    @bar
  end
end

f = Foo.new('test')
puts f #=> "test"
p f #=> "test"
Comments