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!
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 ...
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:
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.
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:
File.foreach('file.txt').map { |line| line.split(' ') }
File.readlines('foo.txt').map &:split
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With