Eivind Eklund
1/29/2008 12:11:00 PM
On Jan 29, 2008 10:47 AM, Pokkai Dokkai <bad_good_lion@yahoo.com> wrote:
> # in source1.rb
> class C1
> def met
> @bb
> puts @bb
> end
> end
>
> # in source2.rb
> require 'source1.rb'
> class C2
> def met
> @aa=10
> C1.new.met
> end
> end
>
>
> #-------------
>
> see above source code
>
> how to pass @aa(in C2) value to @bb(in C1) ?
> @aa is a dynamic value
>
> not allowed conditions are
> 1. class variable ,global variable are NOT allowed
> 2. passing arguments is not allowed( C1.new.met(@aa) is not allow)
> 3. there is no inheritance relationship between class C1,C2
> 4. should not modify class C2 and source2.rb
>
> allowed conditions are
> 1. instance variable ,local variable are allowed
> 2. iterators ,callback are allowed
> 3. allowed to modify class C1 and source1.rb (if needed)
> 4. others are allowed
>
>
> i got this aptitude ruby question from my friend(he got it from an
> interview)
You can open class C2 (or Object), intercept the creation of C2#met
using method_added, and alias C2#met to your own method, thus allowing
passing of the relevant C2 object using thread variables.
You can use set_trace_func to grab the data at the point of call.
You can use ObjectSpace to get at the object (as Luc Heinrich)
mentions, though it's hard to know you've got the right C2 object.
You can tell the interviewer that you dislike the question; it's just
whether you've memorized Ruby internals *for doing ugly hacks*, and
that the only sane thing to do is to add a parameter to the call, or,
if this is an external library, either mail the author of the library
and explain your situation and why you need the parameter, or take the
library "into custody" and maintain it yourself including changes (in
your own version control repository).
Eivind.