非常简单的ruby编程,得到错误而且不理解它

时间:2014-03-11 03:13:35

标签: ruby

我被要求编写基于给定命令

生成输出的ruby程序

The full description

我真的很喜欢红宝石(也许我已经开始红宝石了几个小时)

我收到此错误,请检查我的代码是否存在其他错误:

谢谢。

n `block in each2': undefined method `[]' for #<MyVector:0x00000002c4ad90 @array=[2, 3, 4]> (NoMethodError)

到目前为止我做了什么:

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

1 个答案:

答案 0 :(得分:1)

length.times do |i|
  yield @array[i], a[i]
end

在上面的块中,aMyVector的一个实例。您需要在其上定义[]运算符,可能类似于:

def [](i)
  @array[i]
end