0

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"
5
  • unclear what you're asking. What you want can be achieved my overriding the to_s method Commented Nov 17, 2016 at 14:26
  • you can use attr_reader :bar to get ruby to write the getter for you? Commented Nov 17, 2016 at 14:27
  • I want to get a value without instance method (including attr). For example, instance of String returns its value. When I call its initialize method s = String.new('foo') , I can access its value without instance method s #=> 'foo' . Commented Nov 17, 2016 at 14:30
  • Re-read your question: "how to call a method without a method". It doesn't make sense! Commented Nov 17, 2016 at 14:30
  • You're confusing two things together: string representation of an object and its actual value. These are very different. Commented Nov 17, 2016 at 14:32

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

2 Comments

For p you want .inspect
@YohsukeInoda no you can't use it everywhere: p f.capitalize results in a NoMethodError.
0

The return value of the initialize method is ignored; initialize always returns self, in this case an instance of Foo. Defining a to_s method just defines a string representation of the Foo instance.

f = Foo.new('test')

p f #=> "test"
p f.class #=> Foo

So after ex = Example.new('hello'), ex will always be a Example instance. It can not be a string or whatever.

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.