From: "Jesús Gabriel y Galán" Date: 2010-12-20T17:59:13+09:00 Subject: Re: How to implement such a Domain-Specific-Language (DSL)? On Mon, Dec 20, 2010 at 8:22 AM, Zd Yu wrote: > I need to use Ruby to process performance data and calculate performance > metrics. What I have is a Hash that contains event_name => event_value > mappings. What I want to do is calculating metrics in a elegant style. > > for example: > > events = Hash.new > > # reading the raw data. > # code omitted here. > > # now I get the basic events, like > # events["event_A"] = 123.456 > # events["event_B"] = 456.789 > > # the normal way looks like: > events["metric_A"] = events["event_A"] * 64 / events["event_B"] > > # but what I am wondering if I can do it in an elegant way, like: > metric_A = event_A * 64 / event_B > > Can anybody give some hints? If the only requirement is to have event_A evaluate to events["event_A"] you can do that easily with method_missing. This can give you some ideas: class EventData def initialize events @events = events end def method_missing meth, *args, &blk super unless /\Aevent_/ =~ meth.to_s @events.send(:[], meth.to_s) end end data = EventData.new("event_A" => 123.456, "event_B" => 456.789) metric_A = data.instance_eval { event_A * 64 / event_B } # => 17.2972291364284 You can have a file with only the block for instance_eval for your users to type, with just an extra little bit of work. Jesus.