2012-07-10 46 views
4

我只想写一个包含一个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 
+0

你真的应该使用'print'和'puts',不'printf'。 – Linuxios 2012-07-10 20:22:56

回答

3
# 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

在假设我知道你想要什么,它是这么简单。添加到您的Person类:

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

非常好!这工作。 – user1515888 2012-07-10 20:51:24

+0

@ user1515888:很高兴。 – Linuxios 2012-07-10 20:52:44