[Ruby] copying methods around

Aaron Patterson aaron.patterson at gmail.com
Tue Mar 20 14:43:37 PST 2007


On 3/20/07, Ryan Davis <ryand-ruby at zenspider.com> wrote:
>
> #!/usr/local/bin/ruby -w
>
> require 'ostruct'
>
> class PhilCollins
>    def sussudio
>      "I'm in #{self.class}"
>    end
>
>    def self.easy_lover
>      os = OpenStruct.new
>      class << os
>        # this was as close as I could get. I don't think it is possible
>        # since the classes don't match. Ruby will be pretty strict
>        # about that, but there are ways to cheat... See below.
>        self.send :define_method, :sussudio,
> PhilCollins.instance_method(:sussudio)
>      end
>      os
>    end
> end
>
> msg = PhilCollins.easy_lover.sussudio rescue "nope"
> puts msg


Doh.  Thats where I got stuck.....

require 'rubygems'
> require 'ruby2ruby'
>
> class PeterGabriel
>    def self.shock_the_monkey
>      os = OpenStruct.new
>      class << os
>        eval PhilCollins.new.method(:sussudio).to_ruby
>      end
>      os
>    end
> end
>
> msg = PeterGabriel.shock_the_monkey.sussudio rescue "nope"
> puts msg


I was afraid I would have to do this.  Does R2R not work with instance
methods?  This code seems to return unexpected results:

require 'ruby2ruby'

class JT
  def sexyback
    "I'm in #{self.class}"
  end
end

puts JT.instance_method(:sexyback).to_ruby

That prints out:

def myproc1
  "I'm in #{self.class}"
}

Which does not eval.  Do I /have/ to instantiate the object to use R2R on
it?

-- 
Aaron Patterson
http://tenderlovemaking.com/


More information about the Ruby mailing list