result of assignment is not the return value

N

Nathan Beyer

Given a simple class like this

class MyClass
attr_reader :value
def value=(val)
@value = val.to_s
end
end

Why the the following code return the value passed and not the value
assigned?

c = MyClass.new
result = c.value = 2
puts result
puts c.value

This is currently outputing

2
"2"

The results are the same when MyClass is modified to be this.

class MyClass
attr_reader :value
def value=(val)
@value = val.to_s
return @value
end
end

Shouldn't the result of the 'value=' method be the return value?
 
T

Tony Arcieri

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

Setters always return the value they were originally assigned
 
N

Nathan Beyer

Hi,

In message "Re: result of assignment is not the return value"
=C2=A0 =C2=A0on Fri, 12 Mar 2010 08:55:25 +0900, Nathan Beyer <nbeyer@gma=
il.com said:
|Shouldn't the result of the 'value=3D' method be the return value?

It's a design choice. =C2=A0We defined the value of the assignment as the
value of the right hand expression, not the return value from the
assigning method.

=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=
=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =
=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0matz.

Ahh. Thanks. I figured it was something like that, but I couldn't find
any concrete reference to it.
 
H

Hal Fulton

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

Ahh. Thanks. I figured it was something like that, but I couldn't find
any concrete reference to it.
I have thought about this for awhile. One rationalization is this.

Think of "stacked assignment" which Ruby borrows from C.

x = y = 5

An accessor acts much like a simple assignment:

x = foo.bar = 5 # same as: x = (foo.bar = 5)

In this case, it would be weird if x ended up being anything
other than 5.


Hal
 

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

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top