我试图让自己熟悉Ruby中的矩阵。我试图用字符串格式的输入初始化矩阵。我尝试了以下代码,但它不起作用。请帮助我,我做错了。
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
我想我没有正确初始化矩阵。请帮帮我。
答案 0 :(得分:4)
x = Matrix.rows( input.lines.map { |l| l.split } )
x[0,0] # => "08"
如果你想得到整数,你可以像这样修改它:
Matrix.rows(input.lines.map { |l| l.split.map { |n| n.to_i } })
x[0,0] # => 8
答案 1 :(得分:2)
48是ASCII码'0'。您应该在分割上使用to_i,如下所示:
x = Matrix.rows(input.lines().map { |substr| substr.strip.split(/ /).map {|x| x.to_i} })
请注意分割(/ /),否则,它将被分割为所有字符,最后你会得到0 8 0 2等...