Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby对象数组_Ruby_Object - Fatal编程技术网

Ruby对象数组

Ruby对象数组,ruby,object,Ruby,Object,创建一个类Square,该类具有构造函数和计算正方形面积的方法 class Square def initialize(side) @side = side end def printArea @area = @side * @side puts "Area is: #{@area}" end end 创建2个对象并将其添加到阵列 array = [] array << Square.new(4) array << Square

创建一个类Square,该类具有构造函数和计算正方形面积的方法

class Square
  def initialize(side)
    @side = side
  end

  def printArea
    @area = @side * @side
    puts "Area is: #{@area}"
  end
end
创建2个对象并将其添加到阵列

array = []
array << Square.new(4)
array << Square.new(10)

for i in array do
  array[i].printArea
end
array=[]

数组for
构造很少在Ruby代码中使用。相反,你会写:

array.each do |square|
  square.printArea
end
这将迭代数组并返回每个
square
对象,这也是您的代码所做的
i
不是索引,而是数组中的一个元素

值得注意的是,Ruby强烈鼓励方法名和变量采用
print\u area
的形式

此代码的一种更为Ruby的形式如下所示:

class Square
  attr_accessor :side

  def initialize(side)
    @side = side.to_i
  end

  def area
    @side * @side
  end
end

squares = [ ]
squares << Square.new(10)
squares << Square.new(20)

squares.each do |square|
  puts 'Square of side %d has area %d' % [ square.side, square.area ]
end
classsquare
属性存取器:侧面
def初始化(侧)
@侧面
结束
def区域
@侧面*@侧面
结束
结束
正方形=[]

我相信你想说:

array.each do |sq| 
  sq.printArea 
end

其他答案解释了如何修复。我打算解释你为什么会犯那个错误

请注意您的代码:

array = []
array << Square.new(4)
array << Square.new(10)

for i in array do
    array[i].printArea
end
你会看到类似的东西

Square
Square
Ruby只接受整数作为数组索引。然后,当您提到
array[i]
时,实际上您说的是类似于
array[Square]
的东西,Ruby试图将这些Square对象视为整数,以便将它们用作数组索引。当然,它失败了,因为没有将平方隐式转换为整数,这就是你得到的错误


关于这一点,我在我的博客中做了更多解释。

非常感谢,我不敢相信这会那么容易。我通常会在for和each之间交替使用,但现在我将使用它们。我会写下你的建议,这样我可以进一步改进我的编码方式。是否最好将你的
area
方法写成
side*side
使用包装器?偏好问题
@side*@side
稍微快一点,但这与大多数情况无关
side*side
的工作原理相同。您可能还希望在一行中推送两个对象,如:
array.push Square.new(4),Square.new(10)
Square
Square