【问题标题】:Iterating through array within array and storing to variables遍历数组中的数组并存储到变量中
【发布时间】:2014-12-10 15:21:49
【问题描述】:

我正在寻求以下代码的帮助:

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

谢谢

【问题讨论】:

    标签: ruby arrays object iteration orientation


    【解决方案1】:

    你也可以这样做

     @all_journeys = @journey_lines.map { |line| Journey.new(line[0],line[5],line[6],line[7]) }
    

    【讨论】:

      【解决方案2】:

      我相信这是你需要做的:

      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. 
      

      如果我误解了这个问题,请告诉我。希望对你有帮助:)

      【讨论】:

      • 非常感谢!完美!
      猜你喜欢
      • 2021-10-01
      • 1970-01-01
      • 2015-08-06
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多