开发者

Define a method that is a closure in Ruby

I'm re-defining a method in an object in ruby and I need the new method to be a closure. For example:

def mess_it_up(o)
  x = "blah blah"

  def o.to_s
    puts x  # Wrong! x doesn't exists here, a method is not a closure
  end
end

Now if I define a Proc, it is a closure:

def mess_it_up(o)
  x = "blah blah"

  xp = Proc.new {||
    puts x  # This works
  end

  # but how do I set it to o.to_s.

  def o.to_s
    xp.call  # same problem as befo开发者_如何学JAVAre
  end
end

Any ideas how to do it?

Thanks.


This works (tested in irb):

NOTE: This changes only str - not all instances of String. Read below for details as to why this works

another_str = "please don't change me!"
str =         "ha, try to change my to_s! hahaha!"
proc = Proc.new { "take that, Mr. str!" }

singleton_class = class << str; self; end

singleton_class.send(:define_method, :to_s) do
  proc.call
end

puts str.to_s         #=> "take that, Mr. str!"
puts another_str.to_s #=> "please don't change me!"

# What! We called String#define_method, right?

puts String           #=>  String
puts singleton_class  #=>  #<Class:#<String:0x3c788a0>>

# ... nope! singleton_class is *not* String
# Keep reading if you're curious :)

This works because you are opening str's singleton class and defining a method there. Because this, as well as the call to Module#define_method, have what some call a "flat scope", you're able to access variables that would be out of scope if you used def to_s; 'whatever'; end.

You may want to check out some of these other "metaprogramming spells" here:

media.pragprog.com/titles/ppmetr/spells.pdf


Why does it only change str?

Because Ruby has a couple interesting tricks up it's sleeves. In the Ruby object model, a method invocation results in the reciever searching not only it's class (and it's ancestors), but also it's singleton class (or as Matz would call it, it's eigenclass). This singleton class is what allows you to [re]define a method for a single object. These methods are called "singleton methods". In the example above, we are doing just that - defining a singleton method name to_s. It's functionaly identical to this:

def str.to_s
  ...
end

The only difference is that we get to use a closure when calling Module#define_method, whereas def is a keyword, which results in a change of scope.

Why can't it be simpler?

Well, the good news is that you're programming in Ruby, so feel free to go crazy:

class Object
  def define_method(name, &block)
    singleton = class << self; self; end
    singleton.send(:define_method, name) { |*args| block.call(*args) }
  end
end


str = 'test'
str.define_method(:to_s) { "hello" }
str.define_method(:bark) { "woof!" }
str.define_method(:yell) { "AAAH!" }

puts str.to_s #=> hello
puts str.bark #=> woof!
puts str.yell #=> AAAH!

And, if you're curious...

You know class methods? Or, in some languages, we'd call them static methods? Well, those don't really exist in Ruby. In Ruby, class methods are really just methods defined in the Class object's singleton class.

If that all sounds crazy, take a look at the links I provided above. A lot of Ruby's power can only be tapped into if you know how to metaprogram - in which case you'll really want to know about singleton classes/methods, and more generally, the Ruby object model.

HTH

-Charles


Feature #1082 implemented in Ruby 1.9.2 makes this an easy task with Object#define_singleton_method:

def mess_it_up(o)
  x = "blah blah"

  # Use Object#define_singleton_method to redefine `to_s'
  o.define_singleton_method(:to_s) { x }
end

The concepts involved are still the same as in my previous answer, which provides a more in-depth description of how this works in Ruby's object model, as well as a Object#define_method definition that is conceptually the same as Ruby 1.9.2's Object#define_singleton_method.

Other methods that you might find useful for similar tasks:

  • Object#singleton_class
  • Object#singleton_methods
  • Object#respond_to_missing? (great blog post here)


This seems to work.

class Foo
  def mess_it_up(o)
    x = "blah blah"

    o.instance_variable_set :@to_s_proc, Proc.new { puts x }
    def o.to_s
      @to_s_proc.call
    end
  end
end

var = Object.new
Foo.new.mess_it_up(var)

var.to_s

The problem is that code in def is not evaluated until it's run, and in a new scope. So you have to save the block to an instance variable on the object first and retieve it later.

And define_method doesn't work because it's a class method, meaning you would have to call it on the class of your object, giving that code to ALL instances of that class, and not just this instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜