user1560249
user1560249

Reputation: 453

Ruby - Converting text file to array

I'm very new to Ruby on Rails and am using it to augment some C++ code. My C++ code currently outputs data from a multi-dimensional array to a text file like such:

2 2 2 2 2 3 1 1 1 1 5 2 2 2 2 2 
2 2 2 3 1 1 1 1 1 1 1 1 5 2 2 2 
2 2 1 1 1 1 1 1 1 1 1 1 1 1 2 2 
2 3 1 1 1 1 1 1 1 1 1 1 1 1 5 2 
2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 
3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 5 
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 
6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 
2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 
2 6 1 1 1 1 1 1 1 1 1 1 1 1 4 2 
2 2 1 1 1 1 1 1 1 1 1 1 1 1 2 2 
2 2 2 6 1 1 1 1 1 1 1 1 4 2 2 2 
2 2 2 2 2 6 1 1 1 1 4 2 2 2 2 2 

I'm looking for help in converting this text output into a two-dimensional array for Ruby input with dynamic height/width. So far I've been inputting them by hand into my Ruby code but will soon be doing a lot more tests and I haven't been able to find a way to convert this into a two-dimensional Ruby array so far. Any help would be great!

Upvotes: 10

Views: 11181

Answers (2)

Kyle
Kyle

Reputation: 22258

File.readlines('foo.txt').map &:split

Upvotes: 11

Alistair A. Israel
Alistair A. Israel

Reputation: 6567

File.foreach('file.txt').map { |line| line.split(' ') }

Upvotes: 15

Related Questions