Redefined accessor and return value

Hi,

I have a class that has an attribute named “an_attribute”. I would like
to
define the following function

def an_attribute=(new_value)
return false
end

The problem is every time I call the function, the return value is
always
“new_value” instead of “false.” Is there anyway for me to make it
return
“false”? Of course, the above simplistic example is only used to
illustrate
what I want to ask.

Thanks.

Hi –

On Sun, 19 Jul 2009, Ease B. wrote:

"false." Is there anyway for me to make it return “false”? Of course, the above simplistic example
is only used to illustrate what I want to ask.Â

I don’t think there’s any way. The = methods are engineered so as to
provide assignment-like semantics, and assignments always return their
right-hand side.

You can circumvent this if you use send:

def x=(*)
“Explicit return value”
end
=> nil

self.x = 20
=> 20

send(:x=, 20)
=> “Explicit return value”

(Thanks to Rick DeNatale for reminding me of the send thing in a
recent ruby-talk thread about this :slight_smile:

But using send with a = method kind of defeats the purpose.

David


David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2)
Training! Intro to Ruby, with Black & Kastner, September 14-17
(More info: http://rubyurl.com/vmzN)

David:

Thank you! You saved me so much time. I have decided to name the
setter “set_attribute_A” instead of redefining “attribute_A=” in order
to get a customized return value. Now I am trying to figure out how
to make the default setter private so that outside of the instance,
the setter cannot be called.

I’ve posted another thread regarding that issue. See here:
http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/727e1d3fb3e67987

Thanks,

LBD.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs