Stefano Crocco
6/10/2008 6:12:00 AM
On Tuesday 10 June 2008, progcat@comcast.net wrote:
> I am still learning Ruby and I am trying to get something
> like this to work and am unsure how.
>
> 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
> @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
> 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
>
> Thanks,
> Tom
As first thing, variables like @try and @ones in your code are not class
variables, as the subject of your post implies, but instance variables. Class
variables are something else (their names start with @@, are shared among the
class object itself, its instances, derived class objects and their
instances).
Regarding your question. The only way to access instance variables from
outside the instance is to create accessor methods for them. You can do it
using attr_reader and similar, or you can write them by hand. For example:
class Test
...
def ones
@ones
end
end
I hope this helps
Stefano