gpt4 book ai didi

ruby - 使事物仅在 Ruby block 内可用

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:30 24 4
gpt4 key购买 nike

有没有办法让方法和函数只在 block 内可用?我正在尝试做什么:

some_block do
available_only_in_block
is_this_here?
okay_cool
end

但是 is_this_here?okay_cool 等只能在该 block 内访问,不能在 block 外访问。有什么想法吗?

最佳答案

将包含您希望可用的方法的对象作为参数传递到 block 中。这是一种在 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"

关于ruby - 使事物仅在 Ruby block 内可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1583624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com