我只想寫一個包含一個ID數組的類的Ruby腳本(無欄)。這是我的原班:在Ruby對象類中創建一個數組
# 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
現在我想一個數組叫ID添加到類,我可以將其包含在Struct.new聲明像Struct.new(:FIRST_NAME,:姓氏,:城市,: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
你真的應該使用'print'和'puts',不'printf'。 – Linuxios 2012-07-10 20:22:56