# whats wrong with that
class Whatever
attr_accessor :array @array
def initialize @array = [] @array = ["apple", "banana", "peach"]
end
def array []= (i,value) # setter @array[i] = value
end
def array[] (i) #getter @array[i]
end
end
whatever.array returns the array object, then whatever.array.=(1,2) is
invoked on the array object, you can't define that from your whatever class
unless you define it on the array itself, in the initialize method or
something.
Not to worry, though, array already implements that interface and it does
what you're trying to define. Just do this:
class Whatever
attr_accessor :array
def initialize @array = ["apple", "banana", "peach"]
end
end
···
On Sat, Sep 3, 2011 at 6:16 PM, jack jones <shehio_22@hotmail.com> wrote:
# whats wrong with that
class Whatever
attr_accessor :array @array
def initialize @array = @array = ["apple", "banana", "peach"]
end
def array = (i,value) # setter @array[i] = value
end
def array (i) #getter @array[i]
end
end
# whats wrong with that
class Whatever
attr_accessor :array @array ### THIS IS NOT NECESSARY
def initialize @array = ### THIS IS NOT NECESSARY EITHER @array = ["apple", "banana", "peach"]
end
### THE FOLLOWING IS NOT NECESSARY
def array = (i,value) # setter @array[i] = value
end
def array (i) #getter @array[i]
end
end
this code could read:
class Whatever
attr_accessor :array
def initialize @array = ["apple", "banana", "peach"]
end
you create what's called a 'class instance variable', and you access it
like this:
Dog.x = 10 #setter
puts Dog.x #getter
However, just like with regular instance variables, you have to define
the accessor methods in order to be able to access the 'class instance
variable':
class Dog
@dog
def Dog.x=(val) @x = val
end
def Dog.x @x
end
end
Dog.x = 10
puts Dog.x
--output:--
10
@ variables attach themselves to whatever self is at the moment. Inside
a class, but outside any defs, self is equal to the class. Inside a
def, self is equal to the object that called the method.
Yes, but not from instances of Whatever. You can fake out the object you
return from the array method
class Whatever
# this class does nothing that real arrays don't already do, so...
class FakeArray
def initialize @real_array = ["apple", "banana", "peach"]
end
def =(index, val) @real_array[index] = val
end
def (index) @real_array
end
end
attr_accessor :array
def initialize @array = FakeArray.new
end
end
What are you trying to do that you think you need this capability?
···
On Sat, Sep 3, 2011 at 6:31 PM, jack jones <shehio_22@hotmail.com> wrote:
Isn't there any other way to invoke shehio.array[index] = sth ... Can
this be achieved?