正在完成Def Def奶奶的松樹運動,思想會嘗試並進一步抽取它並儘量避免重複。聾啞人的錯誤奶奶 - 鬆 - 沒有方法
希望我對此的邏輯不是太bizzare只是試圖將事情分解成函數。但現在如果我輸入
Bye
程序立即退出而不繼續執行exitPlan函數。 歡迎任何建議。
puts 'Say something nice to Grandma.'
puts 'You may need to shout > '
speak = gets.strip
counter = 0
speaks(speak)
def speaks(speak)
if speak != 'Bye'
talk()
else
exitPlan()
end
end
def talk()
if speak == speak.downcase
puts 'Huh Speak up Sonny'
counter -= 1
else
year = rand(1930..1951)
puts 'No not Since ' + year.to_s
counter -= 1
end
if counter < 0
counter = 0 # don't want counter going below zero.
end
puts 'Say something nice to Grandma'
speaks()
end
def exitPlan()
counter += 1
unless counter == 3
puts 'Say something nice to Grandma'
speaks()
else
puts 'good night Sonny'
end
end
錯誤
[email protected]:~/Ruby$ ruby -W dGrand.rb
Say something nice to Grandma.
You may need to shout >
Bye
dGrand.rb:6:in `<main>': undefined method `speaks' for main:Object (NoMethodError)
[email protected]:~/Ruby$
是否有任何拋出異常?因爲你的方法不知道變量'counter'和'speak',它們在你的方法範圍之外。將它們從方法傳遞到方法,或者使用類或全局變量檢出。http://www.rubyist.net/~slagell/ruby/globalvars.html – ThoKra 2012-02-01 11:44:10