From: James Edward Gray II Date: 2006-05-09T04:11:40+09:00 Subject: Re: How can I write the awesome kind of code? On May 8, 2006, at 1:59 PM, Pat Maddox wrote: > On 5/8/06, James Edward Gray II wrote: >> On May 8, 2006, at 1:38 PM, Pat Maddox wrote: >> >> > I'm writing a small app to do poker simulations. I read a lot of >> > blogs in which the author shows off his cool DSL. I decided I >> want to >> > be able to specify a poker hand in my app like >> > >> > hand "my_hand" do >> > players 10 >> > chips 1000 >> > end >> > >> > my_hand.foo >> > >> > How can I do something like that? >> >> class Hand >> ... >> end >> >> def hand( ..., &init ) >> Hand.new( ... ).instance_eval(&init) >> end >> >> I really think you'll be happy in the long run though if you drop the >> instance_eval() and pass the hand into the block instead. >> >> James Edward Gray II >> >> > > Okay so now I have > > class Hand > def players(p = nil) > @players = p unless p.nil? > @players > end > > def chips(c = nil) > @chips = c unless c.nil? > @chips > end > end > > def hand(&init) > yield(Hand.new) if block_given? > end > > hand do |h| > h.players 10 > h.chips 1000 > end > > Does that look right? You can remove the &init parameter to hand(), since you are using yield. You may also want to make players() and chips() more Rubyish with players=() and chips=(). To keep the hand object you could have hand return it, or perhaps add it to some global Hash by name. Hope that helps. James Edward Gray II