2016-11-09 238 views
3

创建一个类具有一个构造函数和一个方法来计算正方形区域的类。红宝石数组对象

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隐式转换为整数。

+0

你也可能希望在一行中推两个对象,如:'array.push Square.new(4),Square.new(10) ' –

回答

4

for构造几乎从未在Ruby代码中使用过。相反,你会写:

array.each do |square| 
    square.printArea 
end 

这迭代的数组返回每个square对象,这是你的代码做什么为好。 i不是索引,它是数组中的一个元素。

作为说明,Ruby强烈鼓励方法名称和变量的格式为print_area

这段代码的更红宝石形式如下:

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 

这就将您显示逻辑模型,你应该专注于其他事情的。

+0

非常感谢你,我简直不敢相信那么简单。我通常在for和each之间交替,但我现在要用each。我会写下你的建议,这样我可以进一步改进我的编码方式。 –

+0

使用包装器将'area'方法编写为'side * side'会更好吗? –

+0

优先事项。 '@side * @ side'稍微快一些,但对大多数情况来说这是无关紧要的。 'side * side'将会起作用。 – tadman

3

我相信你想说:

array.each do |sq| 
    sq.printArea 
end 
5

其他的答案解释做什么来解决。我打算解释为什么你有这个错误。

注意你的代码:

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

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

您创建了一个空数组,然后在其中插入两个方形的情况下,对吧?

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

如果你写

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