A
A
Alexander2014-12-10 22:20:20
ruby
Alexander, 2014-12-10 22:20:20

Why is the property value of the object being returned, and not the object itself?

Why is the property value of the object being returned, and not the object itself?

class Point
    attr_accessor :x, :y
    def initialize(x, y) 
        @x, @y = x, y
    end
    def add! ob
        @x += ob.x
        @y += ob.y
    end
    def add ob
        q = self.dup
        q.add! ob
        q                  #!!! Я же возвращаю сам объект а не его свойства
    end
end
po1 = Point.new(3,5)
po2 = Point.new(6,8)
p po1.add po2 # => 9, 13

Or so.
def add! ob
    @x += ob.x
    @y += ob.y
     self
end
def add ob
    q = self.dup
    q.add! ob
end

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Viktor Vsk, 2014-12-10
@viktorvsk

I didn't get any values.
Yes, and in the console there is little point in displaying objects using print, p, puts ... they are brought to the line by default
521e57f0ed8a4f81ae6d799219f673e1.png

A
Alexander, 2014-12-10
@gruut

And I also
found the reason. I have a to_s method defined in Point without it, everything works fine. What is the reason for this behaviour?

def to_s
    "#@x, #@y"
end

it p xjust callsx.to_s

S
Sergey, 2014-12-10
@mastedm

Because it
's really
puts foo.inspect

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question