Ruby对象数组

时间:2016-11-09 23:03:48

标签: 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.new(10)

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

如何访问数组中的对象?我收到一个错误:没有将Square隐式转换为整数。

3 个答案:

答案 0 :(得分:5)

其他答案解释了如何解决问题。我打算解释为什么你有这个错误。

注意你的代码:

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

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

您创建了一个空数组,然后在其中插入了两个Square实例,对吧?

然后,当您撰写for i in array do时,您认为i会包含什么?当然i会包含array 中的对象,即i将包含Square实例!你在说! i in array表示i是数组位置的内容,而不是其索引。

如果你写

for i in array do
    p i.class
end

你会看到像

这样的东西
Square
Square

Ruby只接受整数作为数组索引。然后,当你提到array[i]时,实际上你说的是array[Square],而Ruby试图将这些Square对象视为整数,以便将它们用作数组索引。当然,它失败了,因为有no implicit conversion of Square into Integer,这就是你得到的错误。

我对我的博客this article进行了更多解释。

答案 1 :(得分:4)

在Ruby代码中几乎没有使用for构造。相反,你要写:

array.each do |square|
  square.printArea
end

迭代数组并返回每个square对象,这也是你的代码所做的。 i不是索引,它是数组中的元素。

作为一个注释,Ruby强烈鼓励方法名称和变量采用print_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

这会整合模型之外的显示逻辑,您应该专注于其他事情。

答案 2 :(得分:3)

我相信你想说:

array.each do |sq| 
  sq.printArea 
end