Calling a reader from a writer

C

clintpachl

class Test
def x
@x + '_instance'
end

def x=(v)
@x = v
self.x # also tried `x'
end
end

t = Test.new
puts t.x=('test_x')
=> test_x
puts t.x
=> test_x_instance

Why doesn't the first puts output 'test_x_instance'? I would think that
the self.x call in the writer would call the reader.

How can one call the reader from the writer method?

-pachl
 
N

Nobuyoshi Nakada

Hi,

At Sat, 14 Oct 2006 10:25:11 +0900,
clintpachl wrote in [ruby-talk:219643]:
t = Test.new
puts t.x=('test_x')
=> test_x
puts t.x
=> test_x_instance

An assignment expression always returns the assigned value,
regardless of the implementation of the setter method.
 
D

dblack

Hi --

class Test
def x
@x + '_instance'
end

def x=(v)
@x = v
self.x # also tried `x'
end
end

t = Test.new
puts t.x=('test_x')
=> test_x
puts t.x
=> test_x_instance

Why doesn't the first puts output 'test_x_instance'? I would think that
the self.x call in the writer would call the reader.

This just came up today on IRC. I'd forgotten about it, but was
reminded.

The writer method allows you to use the assignment-like syntax:

t.x = value

Since the goal of this is to make the method call look and feel more
assignment-like, and assignments return their right-hand side, the
writer-method calls also return their right-hand side, rather than the
last value in the method.
How can one call the reader from the writer method?

You are calling the reader, but the magic rhs value overrides it. I
haven't found any way to circumvent it.


David

--
David A. Black | (e-mail address removed)
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org
 
C

clintpachl

reminded.

The writer method allows you to use the assignment-like syntax:

t.x = value

Since the goal of this is to make the method call look and feel more
assignment-like, and assignments return their right-hand side, the
writer-method calls also return their right-hand side, rather than the
last value in the method.


You are calling the reader, but the magic rhs value overrides it. I
haven't found any way to circumvent it.

David, you are right on. Now that I think about it, Ruby does the
natural thing. I was just experimenting and thought it was weird that
my return value was not returning. I guess I needed to step outside the
box.

-pachl
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top