tags:

views:

68

answers:

2

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.

A: 

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...

Zaki
hi, it still gives me 48
Bragboy
it's the exact same code as your accepted solution :)
Zaki
+1  A: 
x = Matrix.rows( input.lines.map { |l| l.split } )
x[0,0]  # => "08"

If you want to get intengers back, you could modify it like so:

Matrix.rows(input.lines.map { |l| l.split.map { |n| n.to_i } })
x[0,0]  # => 8
cam
Thanks it worked great!!
Bragboy