我只想编写一个包含 id 数组的类的 Ruby 脚本(没有 rails)。这是我原来的课程:
# 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
现在我想在类中添加一个名为 ids 的数组,我可以将它包含在 Struct.new 语句中,如 Struct.new(:first_name, :last_name, :city, :ids = Array.new) 还是创建一个实例数组变量或任何定义单独的方法或其他东西?
我希望能够执行以下操作:
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")
并遍历数组
p.ids.each do |i|
puts i
end