Search code examples
rubyjruby

Make array of objects from array of strings


I have an array of strings read from file.

contents = File.readlines('foo.txt')

I can create an some object with string

my_foo = Foo.new("some_text")

I need to make an array of objects Foo made by array of strings contents. How can I do it?


Solution

  • It may be worth to mention, that File.readlines will read everything into memory, what may cause memory issues with large files. Consider using this code:

    File.foreach('foo.txt').map do |line|
      Foo.new(line)
    end
    

    It read file line by line, almost as fast as your code, but more secure.