Hi --
I am still learning Ruby and I am trying to get something
like this to work and am unsure how.
You don't have any class variables in your example, only instance
variables. Class variables look like this: @@var, and in most cases
aren't what you want to use anyway.
I know I could do attr_reader to access "ones" but ones might be an
array, hash, etc.
Is there a way to do something like this:
class Test
def initialize
@try["hashworld"] = 10000
@try is nil at this point; you can't index it.
@ones = 1,2,3,4
end
def addit(one,two)
#can code add one + two, from
#inside and outside?
return(one + two)
end
end
tens = 10,20,30,40,50
a = Test.new
You'll get a fatal error at this point if you run this code.
p a.addit(ones[1],tens[0]) #prints 12
p a.addit(tens[3],ones[0]) #prints 41
p a.addit(tens[3],try["hashworld"]) #prints 10040
You haven't defined try. (It has no connection to the @try inside the
Test#initialize method, which you also haven't defined.)
I'm not sure exactly what you want to do but I think you're
overthinking it. Basically, instance variables (like @try) are visible
only to the object that owns them. If that object wants to expose them
to other objects, it has to provide methods for that purpose.
attr_reader is a macro that writes such a method for you, such that
this:
attr_reader :ones
is the same as this:
def ones
@ones
end
but shorter.
David
···
On Tue, 10 Jun 2008, progcat@comcast.net wrote:
--
Rails training from David A. Black and Ruby Power and Light:
INTRO TO RAILS June 9-12 Berlin
ADVANCING WITH RAILS June 16-19 Berlin
ADVANCING WITH RAILS July 21-24 Edison, NJ
See http://www.rubypal.com for details and updates!