puts box.dup.enlarge(4, 5) -- unexpected result

S

Stefan Salewski

Hello,

I wonder why the statement "puts box.dup.enlarge(4, 5)" below gives
output 8 instead of (0, 1, 6, 8).

Thanks, Stefan Salewski

stefan@AMD64X2 ~/pet $ cat btest.rb
#!/usr/bin/ruby -w
module Bounding
class Box
attr_accessor :x1, :y1, :x2, :y2
def initialize(x1, y1, x2, y2)
@x1, @x2 = [x1, x2].minmax
@y1, @y2 = [y1, y2].minmax
end
def to_s
"(#{@x1}, #{@y1}, #{@x2}, #{@y2})"
end
def enlarge(x, y)
if x < 0 then @x1 += x else @x2 += x end
if y < 0 then @y1 += y else @y2 += y end
end
end
end # Bounding

box = Bounding::Box.new(0, 1, 2, 3)
puts box

#this works as exspected
nb = box.dup
nb.enlarge(4, 5)
puts nb

#this works NOT as expected
puts box.dup.enlarge(4, 5)

stefan@AMD64X2 ~/pet $ ruby btest.rb
(0, 1, 2, 3)
(0, 1, 6, 8)
8
 
G

Gunther Diemant

[Note: parts of this message were removed to make it a legal post.]

A method returns the last evaluated expression. In your case thats @y2 += 5
(which has the result 8).
You could do something like this:
def enlarge(x,y)
#your code

self
end

so the method returns the box itself and not the result of calculationg new
coordinates.
 
S

Stefan Salewski

A method returns the last evaluated expression. In your case thats @y2 += 5
(which has the result 8).
You could do something like this:
def enlarge(x,y)
#your code

self
end

so the method returns the box itself and not the result of calculationg new
coordinates.

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top