创建一个具有构造函数和方法的类Square来计算正方形的面积.
class Square
def initialize(side)
@side = side
end
def printArea
@area = @side * @side
puts "Area is: #{@area}"
end
end
Run Code Online (Sandbox Code Playgroud)
创建2个对象并将它们添加到数组中
array = []
array << Square.new(4)
array << Square.new(10)
for i in array do
array[i].printArea
end
Run Code Online (Sandbox Code Playgroud)
我如何访问数组中的对象?我收到一个错误:没有将Square隐式转换为整数.
其他答案解释了如何解决问题.我打算解释为什么你有这个错误.
注意你的代码:
array = []
array << Square.new(4)
array << Square.new(10)
for i in array do
array[i].printArea
end
Run Code Online (Sandbox Code Playgroud)
你创建了一个空数组,然后插入了两个Square实例,对吧?
那么,当你写作时for i in array do,你认为i会包含什么?当然i会包含的对象中array,即,i将包含广场实例!你在说!i in array说i是数组位置的内容,而不是它的索引.
如果你写
for i in array do
p i.class
end
Run Code Online (Sandbox Code Playgroud)
你会看到类似的东西
Square
Square
Run Code Online (Sandbox Code Playgroud)
碰巧Ruby只接受整数作为数组索引.然后,当你提到array[i]你实际上是在说类似的东西时array[Square],Ruby试图将这些Square对象视为整数,以便将它们用作数组索引.当然,它失败了,因为有no implicit conversion of Square into Integer,这就是你得到的错误.
我更多地解释这是我的博客的这篇文章.