From: Joel VanderWerf Date: 2004-08-04T09:12:41+09:00 Subject: Re: Macros in Ruby Jesse Jones wrote: > For example, suppose you're writing a game and you have a lot of code > that selects behavior based on percentages (75% of hits are normal > blows, 20% are critical hits, and 5% kill your foe out-right for > example). Even in a language as expressive as Ruby this is a bit > awkward to write and not especially intentional. But with macros it can > be written very cleanly: > > percent-case > 0.75 case > normal_hit > end > > 0.20 case > critical_hit > end > > otherwise > kill_foe > end > end It's not really that hard to do something like this in ruby, but it is a little less efficient than it would be with macros. class PercentCase def initialize block @cases = [] instance_eval(&block) end def choose n = rand(100) @cases.each do |percent, block| n -= percent return block.call if n < 0 end otherwise.call end def chance percent, &block @cases << [percent, block] end def otherwise(&block) @otherwise = block end end def percent_case(&block) PercentCase.new(block).choose end 10.times do percent_case do chance 75 do puts "normal_hit" end chance 20 do puts "critical_hit" end otherwise do puts "kill_foe" end end end To make it more efficient, you could keep the PercentCase object around and reuse it each time.