From: Dennis Ranke Date: 2004-08-04T21:21:30+09:00 Subject: Re: Macros in Ruby On Wed, 4 Aug 2004 09:12:41 +0900, Joel VanderWerf wrote: > 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. > > [...] Or you could even do it like this, which looks (to me) even nicer than the macro solution :) class PercentCase def initialize @v = rand(100) end def test(o) @v -= o @v <= 0 end end class Integer alias_method :percentCase, :=== def ===(o) if o.is_a? PercentCase o.test self else percentCase o end end end 10.times do case PercentCase.new when 75 puts 'normal_hit' when 20 puts 'critical_hit' else puts 'kill_foe' end end -- exoticorn/farbrausch