Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 409
user1560249 Avatar asked Jan 29 '13 04:01

user1560249


People also ask

How do I read a file in Ruby?

You can read a file in Ruby like this: 1 Open the file, with the open method. 2 Read the file, the whole file, line by line, or a specific amount of bytes. 3 Close the file, with the close method. More ...

How to convert a string to a number in Ruby?

Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float. Let’s demonstrate this by creating a small program that prompts for two numbers and displays the sum . Create a new Ruby program called adder.rb with the following code:

What is a conversion method in Ruby?

You’re probably familiar with this first group of conversion methods. These methods return a new object of a specific class that represents the current object. “I want to convert the Range 1..10 into an Array that represents that range.” There are ways in which Ruby calls these conversion methods for you implicitly.

How do I convert a string to an array?

You can't convert a string into an array using join. str = "a,b,c" list = str.split (/,/) # => ["a", "b", "c"] list.join ("-") # => "a-b-c" From your comment, it looks like you want to also append a string (or several strings) to the list and then join back into another string. Perhaps like this:


2 Answers

File.foreach('file.txt').map { |line| line.split(' ') }
like image 182
Alistair A. Israel Avatar answered Oct 14 '22 19:10

Alistair A. Israel


File.readlines('foo.txt').map &:split
like image 29
Kyle Avatar answered Oct 14 '22 20:10

Kyle