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
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
end
you create what’s called a ‘class instance variable’, and you access it
using the class like this:
Dog.x = 10 #setter
puts Dog.x #getter
However, just like with regular instance variables, you have to define
accessor methods in order to access a ‘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. If that
doesn’t make any sense, don’t worry about it.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.