[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Using strings to drill down into objects

Pit Capitain

10/15/2007 10:12:00 AM

2007/10/12, Ross X Dawson <Ross.Dawson@aas.com.au>:
> irb(main):001:0> drill_down = lambda do |obj, method_names|
> irb(main):002:1* o ||= obj
> irb(main):003:1> method_names.split('.').each {|m| o = o.send(m)}
> irb(main):004:1> o
> irb(main):005:1> end
> => #<Proc:0x40221e48@(irb):1>
> irb(main):006:0> drill_down.call(1,'succ.to_s')
> => "2"
> irb(main):007:0> drill_down.call(1,'succ.succ.succ.to_s')
> => "4"

Ross, I would implement something like that with Enumerable#inject:

def drill_down(obj, method_names)
method_names.split('.').inject(obj) {|o, m| o.send(m)}
end

But I'm not quite sure that having strings with method calls is the
way to go. Where do the strings with the method names come from? Do
the users of your application have to enter them somewhere? What about
arguments to the method calls?

Regards,
Pit