2010-09-12 12 views
10

Quiero tener una matriz como variable de instancia usando attr_accessor.attr_accessor for array?

¿Pero no es attr_accessor solo para cuerdas?

¿Cómo lo uso en una matriz?

ACTUALIZACIÓN:

Eg. Si desea:

object.array = "cat" 
object.array = "dog" 
pp object.array 
=> ["cat", "dog"] 

Entonces usted tiene que crear esos métodos usted mismo?

+4

attr_accessor funciona para cualquier objeto. ¿Lo has probado? ¿Qué salió mal? – Douglas

+0

@Douglas: Mire la actualización –

+1

Si define un método 'foo =' para que después de hacer 'x.foo = bar',' x.foo' no devuelva 'bar', pueda confundir al diablo con cualquiera quien usa tu clase ¿Por qué no simplemente hacer 'object.array <<" cat "'? – sepp2k

Respuesta

13

Re su actualización

Aunque se puede implementar una clase que actúa como usted describe, se es bastante inusual, y probablemente confundirá a cualquiera que use la clase.

Normalmente los accessors tienen setters y getters. Cuando configura algo usando el setter, obtiene lo mismo del getter. En el siguiente ejemplo, obtienes algo totalmente diferente del comprador. En lugar de utilizar un colocador, probablemente debería usar un método add.

class StrangePropertyAccessorClass 

    def initialize 
    @data = [] 
    end 

    def array=(value) # this is bad, use the add method below instead 
    @data.push(value) 
    end 

    def array 
    @data 
    end 

end 

object = StrangePropertyAccessorClass.new 

object.array = "cat" 
object.array = "dog" 
pp object.array 

El método add se vería así:

def add(value) 
    @data.push(value) 
    end 

... 

object.add "cat" 
object.add "dog" 
pp object.array 
+0

+1 para dar una explicación. También me gusta el << método. Entonces puedes escribir object.array << "cat" en lugar de push. Este es solo un caracter más que object.array = "cat". – Baju

+4

Sí, también tiene sentido en absoluto, a diferencia de 'object.array =" cat "', que es completamente extravagante. –

1

funciona para mí:

class Foo 

    attr_accessor :arr 

    def initialize() 
    @arr = [1,2,3] 
    end 

end 

f = Foo.new 
p f.arr 

devuelve los siguientes

$ ruby /tmp/t.rb 
[1, 2, 3] 
$ 
18
class SomeObject 
    attr_accessor :array 

    def initialize 
    self.array = [] 
    end 
end 

o = SomeObject.new 

o.array.push :a 
o.array.push :b 
o.array << :c 
o.array.inspect #=> [:a, :b, :c] 
1

Creo que hay un caso para este uso. Considere

begin 
    result = do_something(obj) 
    # I can't handle the thought of failure, only one result matters! 
    obj.result = result 
rescue 
    result = try_something_else(obj) 
    # okay so only this result matters! 
    obj.result = result 
end 

Y más tarde

# We don't really care how many times we tried only the last result matters 
obj.result 

Y entonces, por el favorable tenemos

# How many times did we have to try? 
obj.results.count 

Por lo tanto, lo haría:

attr_accessor :results 

def initialize 
    @results = [] 
end 

def result=(x) 
    @results << x 
end 

def result 
    @results.last 
end 

De esta manera result se comporta como usted esperaría t, pero también obtiene el beneficio de acceder a los valores pasados.

Cuestiones relacionadas