在没有 lambda 的情况下定义方法的更简洁的方法



有没有更简单和/或更易读的方法在 Ruby 中创建闭包,以便定义的方法可以访问变量m

我对这里的lambda有轻微的"问题"。

很多时候,我动态定义必须访问局部变量的方法:

例如:

class Comparison
  def income
    123
  end
  def sales
    42342
  end
  # and a dozen of other methods
  # Generate xxx_after_tax for each method
  instance_methods(false).each do |m|
    lambda {
      define_method("#{m}_after_tax") do
        send(m) * 0.9
      end
    }.call
  end
end
class Comparison
  def income
    123
  end
  def sales
    42342
  end
  # and a dozen of other methods
  # Generate xxx_after_tax for each method
  instance_methods(false).each do |m|
    define_method("#{m}_after_tax") do
      send(m) * 0.9
    end
  end
end

常规方法定义不是闭包,但这里你用块调用define_method,块闭包。这应该足够了:

instance_methods(false).each do |m|
  define_method :"#{m}_after_tax" do
    send(m) * 0.9
  end
end

正如 Yuri 指出的那样,lambda是多余的,您可以通过运行此示例看到这一点。

#!/usr/bin/env ruby -w
class Foo
  [:foo, :bar].each do |m|
    define_method("#{m}_dynamic") do
      "Called #{m}"
    end
  end
end
p Foo.new.foo_dynamic # => "Called foo"
  instance_methods(false).each do |m|
    class_eval <<-ERUBY, __FILE__, __LINE__
      def #{m}_after_tax
        #{m} * 0.9
      end
    ERUBY
  end

你可以像这样使用method_missing:

def method_missing(name, *args, &block)
  if name.to_s.match /^([a-z_]+)_after_tax$/
    send($1)
  else
    super
  end
end

我希望这有所帮助。

相关内容

最新更新