所以我給出包含一個文本文件:提取部分
Blade Runner (1982) [117 min]
Full Metal Jacket (1987) [116 min]
Monty Python and the Holy Grail (1975) [91 min]
The Godfather (1972) [175 min]
,並有把它變成這樣:
Movie name: Blade Runner
Movie release year: 1982
Movie length (in mins): 117
Movie name: Full Metal Jacket
Movie release year: 1987
Movie length (in mins): 116
Movie name: Monty Python and the Holy Grail
Movie release year: 1975
Movie length (in mins): 91
Movie name: The Godfather
Movie release year: 1972
Movie length (in mins): 175
首先,我重複在每一行,然後我我以爲我應該迭代字符串的每個部分,但那是我卡住的地方,我該怎麼做?我使用正則表達式嗎?如何保存與正則表達式匹配的特定字符串?
下面是代碼的當前shell,它將三個部分存儲到用於初始化to_s方法以所需格式打印的影片類的變量中。
我知道這在許多方面都不正確,但這就是我尋求幫助的原因。 variable =/regex /是變量分配給正則表達式捕獲的東西的行,以及當正則表達式匹配時/ regex /的時候。
class Movie
def initialize (name, year, length) # constructor
@name = name
@year = year
@length = length
end
def to_s # returns string representation of object
return "Movie Name: " + @name
+ "\nMovie release year: "
+ @year + "\nMovie Length (in min): "
+ @length + "\n"
end
end
$movies = []
File.open("movies.txt").each do |line|
if matches = /(.*)? \((\d+).*?(\d+)/.match(line)
$movies << Movie.new(matches[1], matches[2], matches[3])
end
end
for $movie in $movies do #what u got here is not index but the element in the array
print $movie.to_s
end
編輯:
固定版本的代碼,但打印循環結束時無法正常工作。
Edit2:和nownit呢。謝謝PeterPeiGuo!
@贏郭88888888:你能解釋一下你的編輯?看起來有點多,並且摧毀了問題內容的三分之二,並且甚至沒有寫出適當的編輯摘要。 – BoltClock