1
我有一個從文件中讀取的字符串數組。從字符串數組中創建對象的數組
contents = File.readlines('foo.txt')
我可以用繩子
my_foo = Foo.new("some_text")
我需要通過字符串contents
的陣列製成的物體Foo
數組創建一些對象。我該怎麼做?
我有一個從文件中讀取的字符串數組。從字符串數組中創建對象的數組
contents = File.readlines('foo.txt')
我可以用繩子
my_foo = Foo.new("some_text")
我需要通過字符串contents
的陣列製成的物體Foo
數組創建一些對象。我該怎麼做?
這可能是值得一提,那File.readlines
將讀到的一切到內存中,這可能會使大文件存儲問題。請考慮使用此代碼:
File.foreach('foo.txt').map do |line|
Foo.new(line)
end
它逐行讀取文件中的行,幾乎一樣快,你的代碼,但更安全。
這是你要找的嗎?
contents.map {|i| Foo.new i}
爲什麼不'foos = File.foreach('foo.txt')。map {| line | Foo.new(line)}'而不是聲明'Array'並推入? – engineersmnky
@engineersmnky你說得對,地圖比較好。更新 – djaszczurowski