2
有沒有什麼方法可以使方法和函數只在塊內部可用?我想要做的事:讓事情只在Ruby塊內可用
some_block do
available_only_in_block
is_this_here?
okay_cool
end
但is_this_here?
,okay_cool
等只是塊內被訪問,而不是外面。有什麼想法?
有沒有什麼方法可以使方法和函數只在塊內部可用?我想要做的事:讓事情只在Ruby塊內可用
some_block do
available_only_in_block
is_this_here?
okay_cool
end
但is_this_here?
,okay_cool
等只是塊內被訪問,而不是外面。有什麼想法?
將想要在塊中可用的方法作爲參數傳遞給對象。這是Ruby中廣泛使用的模式,如IO.open
或XML builder。
some_block do |thing|
thing.available_only_in_block
thing.is_this_here?
thing.okay_cool
end
注意,你可以得到更接近你的要求使用instance_eval
或instance_exec
,但通常是一個糟糕的主意,因爲它可以有相當驚人的後果。
class Foo
def bar
"Hello"
end
end
def with_foo &block
Foo.new.instance_exec &block
end
with_foo { bar } #=> "Hello"
bar = 10
with_foo { bar } #=> 10
with_foo { self.bar } #=> "Hello
而如果你在傳遞參數,你總是知道你會提到:
def with_foo
yield Foo.new
end
with_foo { |x| x.bar } #=> "Hello"
bar = 10
x = 20
with_foo { |x| x.bar } #=> "Hello"
這正是我所尋找的,非常感謝 – 2009-10-18 01:17:23
我不知道我知道你想要什麼。 'okay_cool'和公司變量或方法?如果它們是變量,則在塊中聲明它們,它們將在塊中位於本地。 – Telemachus 2009-10-18 00:53:12
他們是方法。 – 2009-10-18 00:59:28