Creating an array in a Ruby object class

I just want to write a Ruby script (without rails) with a class that contains an array of identifiers. Here is my original class:

# define a "Person" class to represent the three expected columns class Person < # a Person has a first name, last name, and city Struct.new(:first_name, :last_name, :city) # a method to print out a csv record for the current Person. # note that you can easily re-arrange columns here, if desired. # also note that this method compensates for blank fields. def print_csv_record last_name.length==0 ? printf(",") : printf("\"%s\",", last_name) first_name.length==0 ? printf(",") : printf("\"%s\",", first_name) city.length==0 ? printf("") : printf("\"%s\"", city) printf("\n") end end 

Now I would like to add an array called ids to the class, can I include it in a Struct.new statement such as Struct.new (: first_name ,: last_name ,: city ,: ids = Array.new) or create an instance array variable or any definition of individual methods or something else?

I would like to be able to do things like:

 p = Person.new p.last_name = "Jim" p.first_name = "Plucket" p.city = "San Diego" #now add things to the array in the object p.ids.push("1") p.ids.push("55") 

and iterate over the array

 p.ids.each do |i| puts i end 
+4
source share
2 answers
 # define a "Person" class to represent the three expected columns class Person attr_accessor :first_name,:last_name,:city ,:ids # Struct.new(:first_name, :last_name, :city ,:ids) #used attr_accessor instead can be used this too def initialize self.ids = [] # on object creation initialize this to an array end # a method to print out a csv record for the current Person. # note that you can easily re-arrange columns here, if desired. # also note that this method compensates for blank fields. def print_csv_record print last_name.empty? ? "," : "\"#{last_name}\"," print first_name.empty? ? "," : "\"#{first_name}\"," print city.empty? ? "" : "\"#{city}\"," p "\n" end end p = Person.new p.last_name = "" p.first_name = "Plucket" p.city = "San Diego" #now add things to the array in the object p.ids.push("1") p.ids.push("55") #iterate p.ids.each do |i| puts i end 
+3
source

Assuming I understand what you want, it's simple. Add this to the Person class:

 def initialize(*) super self.ids = [] end 
+3
source

All Articles