Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attr_accessor for array?

Tags:

ruby

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?

like image 917
never_had_a_name Avatar asked Sep 12 '10 00:09

never_had_a_name


People also ask

What is Attr_accessor?

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.

What is attr_ accessible in Ruby?

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.

What is Attr_reader in Ruby?

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.


1 Answers

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]
like image 84
Ryan McGeary Avatar answered Oct 28 '22 14:10

Ryan McGeary