在上一个问题(Ruby 中的方法是否类似于子例程?)中,我询问了 Ruby 中的方法。现在,在编写我的第一个方法时,我显然遇到了变量范围的问题。当我不调用方法时,下面的程序解释并运行良好learn
。也就是说,如果我删除第 33 行中的调用,一切正常,我在主程序和方法中learn(2)
使用各种变量(例如)似乎并不重要。stimulus[]
但是当我插入调用(并通过u
按键使用它)时,我收到下面的消息,显然表明在方法中使用它是不合适stimulus
的。
brain.rb:26:in `block in learn': undefined local variable or method `stimulus' for main:Object (NameError)
from brain.rb:25:in `each'
from brain.rb:25:in `learn'
from brain.rb:33:in `ucr'
from brain.rb:69:in `<main>'
但是我需要在那里使用它(和大脑),并且它们的当前值由主程序确定。我遇到的有关范围问题的所有答案似乎都相反,即在其他地方的方法中使用变量的问题。我想过让刺激和大脑全球化,但显然这是不行的。如何告诉方法使用程序中的变量?
附言。一旦这个方法有效,我将从程序中的其他六个地方调用它。
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
def read1maybe
return $stdin.read_nonblock 1
rescue Errno::EAGAIN
return ''
end # part of code to get keypress
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
energy=50
# begin defining behavioral methods
def learn(ix)
for j in (7..10)
if stimulus[j]>0 && brain[ix,j] != 0 && brain[ix,j] < 99 then
brain[ix,j]+=int(0.1 * stimulus[j]) * (99-brain[ix,j])
end # if stim
end # for j
end # learn
def ucr
puts "Show UCR"
learn(2)
end
def positive_fixer
puts "Positive fixer"
end
def negative_fixer
puts "Negative fixer"
end
# end defining behavioral methods
# begin main program
while(energy>0) do
(0..10).each {|n| if stimulus[n,0]>2 then stimulus[n,0]+= -2 else stimulus[n,0]==0 end}
input=false
system 'stty cbreak'
look=0
while look < 40000
q = read1maybe
break if q.length > 0
look +=1
end # while look
case q
when "f" then stimulus[4,0]=9 and puts "Good!"
when "p" then stimulus[5,0]=9 and puts "Bad!"
when "u" then stimulus[6,0]=9
when "l" then stimulus[7,0]=9 and stimulus[8,0]=9 and puts "ight on"
when "c" then stimulus[9,0]=9 and puts " BUZZZ"
input=true
end # case q
system 'stty cooked'
if input==false then (0..3).each { |n| stimulus[n,0]=rand(25)} end
behavior=brain*stimulus
if behavior[0,0] > t then positive_fixer end
if behavior[1,0] > t then negative_fixer end
if behavior[2,0] > t then ucr end
if behavior [3,0] > t then puts "show operant 1" end # and stimulus[10,0]=9
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
energy += -1
# temp to test development of memory
puts brain[2,9]
end # while energy > 0
puts
puts "It's dead Jim."
# end main program