3

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
1
  • You should really be using print and puts, not printf. Commented Jul 10, 2012 at 20:22

2 Answers 2

2
# 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
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.