Ruby array of objects

Allen M

Creating a class Square which has a constructor and a methiod to calculate the area of the square.

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

  def printArea
    @area = @side * @side
    puts "Area is: #{@area}"
  end
end

Creating 2 objects and adding them to an array

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

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

How do i acces the objects inside the array? I get an error: no implicit conversion of Square into Integer.

tadman

The for construct is hardly ever used in Ruby code. Instead you'd write:

array.each do |square|
  square.printArea
end

This iterates over the array and returns each square object, which is what your code does as well. i is not an index, it's an element in the array.

As a note, Ruby strongly encourages method names and variables to be of the form print_area.

A more Ruby form of this code looks like this:

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

This consolidates your display logic outside of the model where you should be focused on other things.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事