How to make an object to return its own value

#1

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)
end
def to_s
@value.to_s
end
end

IRB:
test = MyClass.new(2.0)
test
#<MyClass:0x007f9632191250 @value=2.0>

#2

To get value out of variables use: puts test

Discussed here: https://stackoverflow.com/questions/8125946/ruby-object-prints-out-as-pointer

#3

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

test
=> 2.02

#4

add additional method inside your class:

def inspect
@value.to_s
end

1 Like
#5

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.

Example

p "#{Array.new}" == Array.new.to_s         # => true
p "#{Array.new}" == Array.new.inspect    # => 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):005:1> 
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):009:1> 
p.rb(main):010:1> 	alias :inspect :to_s
p.rb(main):011:1> 
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
p.rb(main):016:0> 
p.rb(main):017:0> MyClass.new(5)
=> 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
#6

Thank you :slight_smile: