1

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

why not foos = File.foreach('foo.txt').map { |line| Foo.new(line) } rather than declaring the Array and pushing into it?
@engineersmnky you are right, map is better. updated
3

Is this what your looking for?

contents.map {|i| Foo.new i}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.