【发布时间】:2012-03-20 12:11:40
【问题描述】:
我想用用户指定的块替换对象方法的实现。在 JavaScript 中,这很容易实现:
function Foo() {
this.bar = function(x) { console.log(x) }
}
foo = new Foo()
foo.bar("baz")
foo.bar = function(x) { console.error(x) }
foo.bar("baz")
在 C# 中也很简单
class Foo
{
public Action<string> Bar { get; set; }
public Foo()
{
Bar = x => Console.WriteLine(x);
}
}
var foo = Foo.new();
foo.Bar("baz");
foo.Bar = x => Console.Error.WriteLine(x);
foo.Bar("baz");
但是我怎样才能在 Ruby 中做同样的事情呢?我有一个将 lambda 存储在实例变量中并且方法调用 lambda 的解决方案,但我不太喜欢开销和语法
class Foo
def initialize
@bar = lambda {|x| puts x}
end
def bar x
@bar.call x
end
def bar= blk
@bar = blk
end
end
foo = Foo.new
foo.bar "baz"
foo.bar= lambda {|x| puts "*" + x.to_s}
foo.bar "baz"
我想要这样的语法:
foo.bar do |x|
puts "*" + x.to_s
end
foo.bar "baz"
我想出了以下代码
class Foo
def bar x = nil, &blk
if (block_given?)
@bar = blk
elsif (@bar.nil?)
puts x
else
@bar.call x
end
end
end
但这对于不止一个参数来说有点难看,而且仍然感觉不“正确”。我也可以定义一个 set_bar 方法,但我也不喜欢这样:)。
class Foo
def bar x
if (@bar.nil?)
puts x
else
@bar.call x
end
end
def set_bar &blk
@bar = blk
end
end
所以问题是:有没有更好的方法来做到这一点,如果没有,您更喜欢哪种方式
编辑: @welldan97 的方法有效,但我失去了局部变量范围,即
prefix = "*"
def foo.bar x
puts prefix + x.to_s
end
不起作用。我想我必须坚持使用 lambda 才能工作?
【问题讨论】:
标签: ruby metaprogramming