Tonight I’m exploring the problem of tossing a value at a class instance
and getting a value back - having it behave like a method, in other
words. I’ve not looked at this before, and I don’t have much confidence
about what I’m doing. I have a simple example from Thomas 3rd ed., and
have modified it a bit. It’s not working as I’d expect - at all.
The code:
=== begin code
test.rb
def main
test = Test.new
puts ‘bye’ # <=========== line 6
end
class Test
def t1=(val)
@val = val
return 99
end
def t2=(val)
@val = val * 2
return 99
end
end
%w(rubygems ruby-debug).each{ |lib| require lib }
Debugger.start
debugger
main
=== end code
I start this, and the debugger stops it. I put a break point a line 6,
and continue.
With execution stopped, I enter at the command line:
(rdb:1) p test.t2 = 2
2
I should have gotten 4. I only ever get back the same number I put in.
Can someone tell me what the problem is, and what I have to do to get
test.t2 to do this simple thing I’m asking of it?
My other question: the “return 99” business is from Thomas. He doesn’t
explain it. I’ve been reading about “return” and I cannot account for
why it’s there. It doesn’t seem to do any thing. Can someone explain
THAT.
Finally, is this general approach I’m taking the best or usual way to
send data to a class method and get some output? Until now, I thought I
had to read an accessor variable to get output back, but I’m thinking
now that that is probably NOT the best way.
What I’m wanting to do, say, create a file object which gives me more
data when I call upon it (it’ll read a record and do some processing,
then pass back the results. Normally I’d use a method, but I’m trying to
become more “classy” in my programming, hence this effort. I’m basically
still struggling to find a good reason to use a class at all. So far,
it’s proven far too difficult to get something OUT of a class instance.
I don’t see the point of the bother, yet. I’m hoping some enlightenment
will arrive soon.
As always, much thanks for all contributions!
Tom
–
Tom C., MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< [email protected] >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)