Now I want C2 to have f method so that I can call C2.new.f.
Select lines 2-4.
Copy.
Move caret inside C2.
Paste.
Ruby's methods are not first-class functions like Lua or JavaScript
have. Other, first-class functions exist (procs/lambdas), but Methods
are not these.
Others have given you good suggestions (modules, inheritance). I think
the most important advice is to describe what you want to do instead of
how you think you might want to accomplish it.
Here's one other technique, that very likely is too complicated and
isn't what you wanted. It gives C2 access to the proc defined at the
class level of C1, which it can invoke on itself.
Of course, any methods you try to invoke on 'self' inside that proc must
exist both for the C1 and the C2 instance...in which case, you probably
wanted inheritance or module inclusion anyhow.
class C1
class << self
attr_reader :complex_stuff
end
@complex_stuff = lambda{
puts "My encoded representation is #{self.inspect.reverse}"
}
def initialize( name )
@name = name
end
def do_complex_stuff
self.instance_eval( &self.class.complex_stuff )
end
end
C1.new( 'charlie' ).do_complex_stuff
#=> My encoded representation is >"eilrahc"=eman@ 8194382x0:1C<#
class C2
def do_complex_stuff
self.instance_eval( &C1.complex_stuff )
end
end
C2.new.do_complex_stuff
#=> My encoded representation is >0714382x0:2C<#
···
From: Sam Kong [mailto:sam.s.kong@gmail.com]