我正在寻找以下代码的帮助:
class Journey
@@journey_count = 0
def initialize (reg, driver, destin1, destin2)
@reg = reg
@driver = driver
@destin1 = destin1
@destin2 = destin2
@@journey_count += 1
end
end
class Destination
def initialize (eta, starttime, endtime, punctuality)
@eta = eta
@starttime = starttime
@endtime = endtime
@punctuality = punctuality
end
end
# save text file to string
data = File.read("workdata.txt")
# split string into blocks of text relevant to each journey
journeys = data.split(/\n\s\n/)
# store the amount of journeys as a variable called journeys_size
journeys_size = journeys.length
# puts journeys_size
# split each journey into lines and save to an array called "journey_lines"
@journey_lines = journeys.map { |i| i.split(/\n/) }
现在我有一个数组数组。我想遍历主数组的每个元素(也是数组),并根据上面定义的旅程类将内部数组的某些行存储到一个新对象中。我知道这是不正确的,但有点像......
@journey_lines.each do |line0, line5, line6, line7|
@@journey_count + =1 = journey.new
line1 = @reg
line2 = @driver
line3 = @destin1
line4 = @destin2
end
由于
答案 0 :(得分:0)
我相信这就是你需要做的事情:
all_journey_objects = []
@journey_lines.each do |line|
#line should be an array
#line[0] should be pointing to corresponding 'reg'
#line[5] should be pointing to corresponding 'driver'
#line[6] should be pointing to corresponding 'destin1'
#line[7] should be pointing to corresponding 'destin2'
#since you have already defined initialize method in Journey class, can create an object this way
journey = Journey.new(line[0] , line[5] , line[6] , line[7])
all_journey_objects << journey
end
# all_journey_objects will be an array of all the new Journey objects that you have initialized.
如果我误解了这个问题,请告诉我。希望它有帮助:)
答案 1 :(得分:0)
你也可以这样做
@all_journeys = @journey_lines.map { |line| Journey.new(line[0],line[5],line[6],line[7]) }