user1515888
user1515888

Reputation: 33

Creating an array within a Ruby object class

I just want to write a Ruby script (no rails) with a class that contains an array of ids. 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 the Struct.new statement like Struct.new(:first_name, :last_name, :city, :ids = Array.new) or create an instance array variable or any define separate methods or something else?

I would like to then 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

Upvotes: 3

Views: 10561

Answers (2)

Pritesh Jain
Pritesh Jain

Reputation: 9146

# 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

Upvotes: 2

Linuxios
Linuxios

Reputation: 35803

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

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

Upvotes: 2

Related Questions