In trying to learn Ruby, I started a program to create squares.
In defining class Square, I want each new instance to have all the
properties of a square, including its grid-like rows and columns. I
wanted the initialize method to make each new instance an array of
arrays from which I can form rows, columns, sides and diagonals. The
grid could then be used for various applications including magic
squares. However, I don’t know how to reference the instance within the
initialize method so that the instance will be an array of arrays by
virtue of being an instance of class Square. Instead, I tried to create
instance methods. The methods work except mksq, which is supposed to
create the array of arrays. Result = undefined method ‘mksq’ for
[]:square.
My code is in the attached files, with excerpts below. I would
appreciate any insight as to why the mksq method doesn’t work.
I would also appreciate any insight as to whether there is a way to
reference the instance within the class methods.
excerpt from ‘ClassSquare.rb’
def mksq
@square = []
0.upto(@ord-1) do |j|
@square[j].push(Array.new)
0.upto(@ord-1) do |i|
@square[j][i].push(0)
end
end
@square
end
‘MakeSq.rb’
require_relative ‘ClassSquare.rb’
sq = Square.new
puts “Class = #{sq.class}”
puts “Ord = #{sq.ord}; magic constant = #{sq.m}”
puts “Area = #{sq.area} square units”
print “\nValues = #{sq.values}\n”
sq.push(sq.mksq)
0.upto(sq.ord-1) do |i|
puts sq[i]
end