How to make an object to return its own value

How can I bring a my own class to return the variable content “value” when I use it in a program?

For example when I create a numeric object
x = 1.0 and call it IRB then it returns 1.0

But when I call my own class below it returns the object_id and the value

class MyClass
def initialize(value)
@value = do_something(value)
def to_s

test =
#<MyClass:0x007f9632191250 @value=2.0>

To get value out of variables use: puts test

Discussed here:

I want it without having to use puts. When I enter test, I want to get a numeric result

=> 2.02

add additional method inside your class:

def inspect

1 Like

When you create a new instance of classes like Hash, Array, Integer, Float, String, and others, you call the inspect method. But when you call puts, print, printf, sprintf, you call the to_s method.


p "#{}" ==         # => true
p "#{}" ==    # => true

How to Properly Code Your Class?

You can simply define the alias method. If you think your inspect method returns the value that the to_s method returns, simply alias inspect(). Let’s take a look:

> irb p.rb 
p.rb(main):001:0> class MyClass
p.rb(main):002:1> 	def initialize(value)
p.rb(main):003:2> 		@value = do_something(value)
p.rb(main):004:2> 	end
p.rb(main):006:1> 	def to_s
p.rb(main):007:2> 		@value.to_s
p.rb(main):008:2> 	end
p.rb(main):010:1> 	alias :inspect :to_s
p.rb(main):012:1> 	def do_something(*args)
p.rb(main):013:2> 		args.sum
p.rb(main):014:2> 	end
p.rb(main):015:1> end
=> :do_something
=> 5

What IRB does is printing the return value by calling the inspect method. So IRB is also called REPL.
Also, you can define inspect instead of aliasing it!

Hope this helps!

1 Like

Thank you :slight_smile:

You must add a method, the methods return the result of the last evaluated expression or


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs