Reputation: 35542
I was trying to get familiarize myself with matrices in Ruby. I am trying to initialize a matrix with a input in string format. I tried the following code, but its not working. Please help me what I'm doing wrong.
input =
'08 02 22 97
49 49 99 40
81 49 31 73
52 70 95 23'
x = Matrix.rows(input.lines() { |substr| substr.strip.split(//) })
puts x[0,0] #I expect 8. but I am getting 48 which is not even in the matrix
I guess I am not initializing the matrix properly. Please help me.
Upvotes: 0
Views: 2396
Reputation: 14222
x = Matrix.rows( input.lines.map { |l| l.split } )
x[0,0] # => "08"
If you want to get integers back, you could modify it like so:
Matrix.rows(input.lines.map { |l| l.split.map { |n| n.to_i } })
x[0,0] # => 8
Upvotes: 4
Reputation: 1101
48 is the ASCII code of '0'. You should use to_i on the split like this:
x = Matrix.rows(input.lines().map { |substr| substr.strip.split(/ /).map {|x| x.to_i} })
Please also note the split(/ /), otherwise, it would be split for all characters and you end up with 0 8 0 2 etc...
Upvotes: 2