在Ruby对象类中创建数组
发布时间:2020-12-17 03:03:23 所属栏目:百科 来源:网络整理
导读:我只想编写一个 Ruby脚本(没有rails),其中包含一个包含id数组的类.这是我原来的课程: # define a "Person" class to represent the three expected columnsclass Person # a Person has a first name,last name,and city Struct.new(:first_name,:last_name
我只想编写一个
Ruby脚本(没有rails),其中包含一个包含id数组的类.这是我原来的课程:
# 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(",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 解决方法# define a "Person" class to represent the three expected columns class Person attr_accessor :first_name,:city,:ids # Struct.new(:first_name,: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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |