我被要求编写基于给定命令
生成输出的ruby程序我真的很喜欢红宝石(也许我已经开始红宝石了几个小时)
当我运行程序时,我进入无限循环,我不明白为什么。
谢谢。
到目前为止我做了什么:
# MyVector Class
class MyVector
def initialize (a)
if !(a.instance_of? Array)
raise "ARGUMENT OF INITIALIZER MUST BE AN ARRAY"
else
@array = a
end
end
def array
@array
end
def to_s
@array.to_s
end
def length
@array.length
end
def [](i)
@array[i]
end
def each2(a)
raise Error, "INTEGER IS NOT LIKE VECTOR" if a.kind_of?(Integer)
Vector.Raise Error if length != a.length
return to_enum(:each2, a) unless block_given?
length.times do |i|
yield @array[i], a[i]
end
self
end
def * (a)
Vector.Raise Error if length != a.length
p = 0
each2(a) {|a1, a2|p += a1 * a2}
p
end
end
# MyMatrix Class
class MyMatrix
def initialize a
@array=Array.new(a.length)
i=0
while(i<a.length)
@array[i]=MyVector.new(a[i])
end
end
def to_s
@array.to_s
end
def transpose
size=vectors[0].length
arr= Array.new(size)
i=0
while i<size
a=Array.new(vector.length)
j=0
while j<a.length
a[j]=vectors[j].arr[i]
j+=1
end
arr[i]=a
i+=1
end
arr[i]=a
i+=1
end
def *m
if !(m instance_of? MyMatrix)
raise Error
a=Array.new(@array.length)
i=0
while (i<@array.length)
a[i]=@array[i]*m
i=i+1
end
end
end
end
输入:
Test code
v = MyVector.new([1,2,3])
puts "v = " + v.to_s
v1 = MyVector.new([2,3,4])
puts "v1 = " + v1.to_s
puts "v * v1 = " + (v * v1).to_s
m = MyMatrix.new([[1,2], [1, 2], [1, 2]])
puts "m = " + m.to_s + "\n"
puts "v * m = " + (v * m).to_s
m1 = MyMatrix.new([[1, 2, 3], [2, 3, 4]])
puts "m1 = " + m1.to_s + "\n"
puts "m * m1 = " + (m * m1).to_s
puts "m1 * m = " + (m1 * m).to_s
期望的输出:
v = 1 2 3
v1 = 2 3 4
v * v1 = 20
m =
1 2
1 2
1 2
v * m = 6 12
m1 =
1 2 3
2 3 4
m * m1 =
5 8 11
5 8 11
5 8 11
m1 * m =
6 12
9 18
答案 0 :(得分:1)
要回答无限循环问题,您似乎忘记在i += 1
类的#initialize
方法中添加Matrix
。
但是,您将在代码中遇到更多错误,例如,您正在检查未定义的Matrix对象的length
,并在each2
中迭代Matrix对象在Vector
类内部定义,需要该对象为Enumerable(Array / Hash等)。由于Matrix类不是Enumerator
,因此会抛出错误。 These are一些很好的资源可以帮助您了解强大的Enumerator module是如何运作的。
熟悉语法和结构后,请务必使用Pry tool。它将是您调试Ruby代码的最好朋友。