I’ve written the program below previously in Basic and Pascal, now I’m porting it to Ruby. The puts in lines 20..26 stand in for what were calls to subroutines (gosub..return) in basic and pascal. I don’t find subroutines in Ruby. Would I create a method for each of these? The subroutines are graphical displays, manipulations of the brain matrix, etc. It’s important that when they finish, I return to the same spot.
(If it is useful: external events, e.g., key presses, put values in the stimulus matrix, that, when multiplied by the brain matrix generate the values in the behavior matrix.)
A more elegant way of doing lines 20..26 is also welcome.
Thanks.
require 'matrix'
class Matrix
def []=(i, j, x)
@rows[i][j] = x
end
end #code to allow putting individual elements in matrix at i,j
brain= Matrix[ [0,0,0,0,99,0,0,0,0,1,0],
[0,0,0,0,0,99,0,0,0,1,0],
[0,0,0,0,0,0,99,0,0,1,0],
[25,0,0,0,0,0,0,1,-1,1,-99],
[0,23,0,0,0,0,0,1,-1,1,1],
[0,0,24,0,0,0,0,1,-1,1,1],
[0,0,0,22,0,0,0,1,-1,1,1] ]
stimulus=Matrix.column_vector([0,0,0,0,0,0,0,0,0,0,0])
behavior=Matrix.column_vector([0,0,0,0,0,0,0])
t=500 # t=threshold
behavior=brain*stimulus
if behavior[0,0] > t then puts "do poistive fixer" end
if behavior[1,0] > t then puts "do negative fixer" end
if behavior[2,0] > t then puts "show UCR" end
if behavior [3,0] > t then puts "show operant 1" end
if behavior[4,0] > t then puts "show operant 2" end
if behavior[5,0] > t then puts "show operant 3" end
if behavior[6,0] > t then puts "show operant 4" end
Yes, a method is a reusable chunk of code, just like a subroutine.
The quickest refactor of 20-26 would look like this:
Whether or not you prefer the minimal savings is a matter of opinion.
The next level of refactoring might be as simple as putting the strings in an array (untested but close):
As Tin Man notes you could use the array directly:
Etc.