gpt4 book ai didi

ruby - 在 Ruby 对象类中创建数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:07 25 4
gpt4 key购买 nike

我只想用一个包含 ID 数组的类编写一个 Ruby 脚本(没有 Rails)。这是我原来的类(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

现在我想在类中添加一个名为 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,: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

关于ruby - 在 Ruby 对象类中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11421035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com