tldr:我在启动时生成多个类似的对象,并希望能够查看,编辑或以其他方式操作每个对象。你会怎么做?
我写的程序记录了车辆的详细信息(品牌,型号,颜色,描述,制造日期和注册号)。以前我生成对象并将数据转储到全局变量中,然后我用它来搜索,编辑和保存。
我现在试图取消这个变量并直接与对象交互。
我发现的所有教程在启动对象时似乎都依赖于硬编码变量。例如
class Paragraph
attr_accessor :font, :size, :weight, :justification
end
p = Paragraph.new
p.font = 'Times'
p.size = 14
p.weight = 300
p.justification = 'right'
puts "#{p.font}, #{p.size}, #{p.weight}, #{p.justification}"
# => Times, 14, 300, right
所以你可以使用p.whatever来调用每个字段。在我的脚本中,我不能硬编码,因为我不知道将创建多少个对象。这是我的脚本的开始,它从json加载以前的记录并重新创建对象。
require 'json'
class Car
attr_accessor :vrm
attr_accessor :make
attr_accessor :model
attr_accessor :description
attr_accessor :colour
attr_accessor :date
def initialize(aMake, aModel, aDescription, aColour, aVRM, aManufactureDate)
@vrm = aVRM
@make = aMake
@model = aModel
@description = aDescription
@colour = aColour
@date = aManufactureDate
end
def text_format
return "Vehicle details: Reg number #{@vrm}, Make #{@make}, Model #{@model}, Description #{@description}, Colour: #{@colour}, Date #{@date}"
end
end
def open_file
if File.file?("vehicles.json")
File.open('vehicles.json') do |f|
$all_vehicles = JSON.parse(f.read)
end
$all_vehicles.each do |a_vehicle|
Car.new(a_vehicle[1][0], a_vehicle[1][1], a_vehicle[1][3], a_vehicle[1][2], a_vehicle[0], a_vehicle[1][4])
end
count
p $vehicle_id
else
p 'Unable to find file, creating blank file'
save_to_file
end
end
我可以在创建数组时捕获数组中的对象ID,但我无法看到如何使用它来调用对象。
$all_vehicles.each do |a_vehicle|
file << Car.new(a_vehicle[1][0], a_vehicle[1][1], a_vehicle[1][3], a_vehicle[1][2], a_vehicle[0], a_vehicle[1][4])
$vehicle_id << file.object_id
end
我想做这样的事情
def search
list_vehicles = all Car objects
list_vehicles.each do |vehicle|
compare vehicle with search criteria
end
end
您可以使用Hash
而不是Array
来存储您的实例,并使用vrm
作为关键:
# initialize the hash
cars_by_vrm = {}
# when creating the instances
$all_vehicles.each do |a_vehicle|
car = Car.new(a_vehicle[1][0], a_vehicle[1][1], a_vehicle[1][3], a_vehicle[1][2], a_vehicle[0], a_vehicle[1][4])
cars_by_vrm[car.vrm] = car
end
# when you want to load a specific car later on
car = cars_by_vrm['some_vrm']
注意将cars_by_vrm
替换为在您的应用程序中有意义的变量类型或方法。