以下代码会覆盖@journey_lines 10次,只留下最后一次保存为数组的旅程。我想为每个旅程(1到10)创建一个新的数组对象。
# 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
# Split each journey into lines and save to an array called "journey_lines"
journeys[1..10].each { |i| @journey_lines = i.split(/\n/) }
# Inspect journey_lines
p @journey_lines
有没有办法将变量插入迭代值?有点像...
journeys[1..#journeys.size].each { |i| @journey_lines[1..#journeys_size] = i.split(/\n/) }
或者更好的方式一起完成这一切。我已经尝试过一段时间了。请帮忙!
答案 0 :(得分:0)
您应该使用map
方法
@journey_lines = journey.map {|item| item.split(/\n/) }