From: Pat Maddox Date: 2006-05-09T04:26:22+09:00 Subject: Re: How can I write the awesome kind of code? On 5/8/06, James Edward Gray II wrote: > 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 > > > I took out &init, I understand why I don't need that in there. However after doing all this, I'm not sure I get any benefit, particularly if I stick to the more Rubyish players= and chips= hand "my_hand" do |h| h.chips = 1000 h.players = 10 end vs my_hand = Hand.new my_hand.chips = 1000 my_hand.players = 10 It's basically the same... Pat