Forum: Ruby Can I return the value of val with: def active=(val)?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Anita A. (Guest)
on 2009-01-06 23:57
How to return the value of val?
If I write:
def active=(val)
  if user.active
   val = t
  else
   val = z
end
I never saw a method using name=(value), I cannot use active? because
val needs to be different than true or false.
Anyone? Have you seen such a method before? where? I need an example
Tim H. (Guest)
on 2009-01-07 01:04
(Received via mailing list)
Anita A. wrote:
> Anyone? Have you seen such a method before? where? I need an example
Have you tried it? It's easy to find out:

rb(main):009:0> class Foo
irb(main):010:1> def x=(v)
irb(main):011:2> puts "Hello from x=!"
irb(main):012:2> @x = v
irb(main):013:2> v
irb(main):014:2> end
irb(main):015:1> end
=> nil
irb(main):016:0> f = Foo.new
=> #<Foo:0x4ad350>
irb(main):017:0> f.x = 'set x to this string'
Hello from x=!
=> "set x to this string"
Gary W. (Guest)
on 2009-01-07 01:05
(Received via mailing list)
On Jan 6, 2009, at 4:58 PM, Anita A. wrote:

> Anyone? Have you seen such a method before? where? I need an example
It isn't clear what you are trying to accomplish.  In your example,
where are t and z coming from?  Are they attributes of the class?  Can
you show us how you intend to use this method (rather than the
definition shown above).

I'm not sure if this is important to your use case, but the return
value of an assignment method is ignored by Ruby so as to not confuse
the assignment semantics:

self.active = x

will always evaluate to x regardless of how the method active= is
written.
This topic is locked and can not be replied to.