I want to have an array as a instance variable using attr_accessor
.
But isn't attr_accessor
only for strings?
How do I use it on an array?
UPDATE:
Eg. If you want:
object.array = "cat"
object.array = "dog"
pp object.array
=> ["cat", "dog"]
Then you have to create those methods yourself?
attr_accessor is a shortcut method when you need both attr_reader and attr_writer . Since both reading and writing data are common, the idiomatic method attr_accessor is quite useful.
attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.
Summary. attr_reader and attr_writer in Ruby allow us to access and modify instance variables using the . notation by creating getter and setter methods automatically. These methods allow us to access instance variables from outside the scope of the class definition.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With