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


#1

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


#2

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”


#3

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.