inner_method
只在outer_method
内被调用,其参数将始终与outer_method
相同。
这有效:
def outer_method(word)
inner_method(word)
puts word + " are like candy."
end
def inner_method(same_word)
puts "I really love " + same_word + "!"
end
outer_method("onions")
但这不是:
def outer_method(word)
inner_method
puts word + "tastes like candy."
end
def inner_method
puts "I really love " + word + "!"
end
outer_method("onions")
似乎inner_method
对word
的引用未被outer_method
注册。有更好的方法吗?
(我意识到在上面的例子中没有理由单独inner_method
;为了清楚起见,这是简化的)
答案 0 :(得分:1)
老实说,我认为你的第一种技术是最好的方式,完全是惯用语。不过,这是另一种选择:
def outer_method(word)
inner_lambda = lambda do
puts "I really love " + word + "!"
end
inner_lambda.call
puts word + " tastes like candy."
end
outer_method("onions")
lambda
创建一个词法闭包,这意味着它捕获周围环境,包括对word
的引用。
答案 1 :(得分:1)
您的问题有两个问题。浅薄的是你学习Ruby的语法。更深层次的是学习正确的编码模式。在您的情况下, word 对象需要存在:
class MyWord < String
def singular?; @singular end
def initialize **setup
singular, plural = setup[:singular], setup[:plural]
if singular then @singular = true
super singular
elsif plural then @singular = false
super plural
else fail ArgumentError, "Bad MyWord constructor arguments!" end
end
def interjection_1
"I really love #{self}!"
end
def interjection_2
"#{capitalize} #{singular? ? 'is' : 'are'} like cand#{singular? ? 'y' : 'ies'}!"
end
def hysteria
puts interjection_1
puts interjection_2
end
end
然后:
MyWord.new( plural: "onions" ).hysteria