Friday, February 18, 2011

FizzBuzz Kata: minimal solution

Trying to find a minimal solution for the FizzBuzz Kata in Smalltalk:

fb := [:counter| |rules|
       rules := {15->'FizzBuzz'. 5->'Buzz'. 3->'Fizz'. 1->counter}.
       rightRule := rules detect: [:aRule| counter \\ aRule key == 0].
       rightRule value].  

self assert: (fb value: 7) == 7.
self assert: (fb value: 3) == 'Fizz'.
self assert: (fb value: 5) == 'Buzz'.
self assert: (fb value: 15) == 'FizzBuzz'.

1 to: 100 do: [:counter | 
                 show: (fb value: counter) asString;

Update: Little variant from Alexandre:
rightRule := rules detect: [:aRule| counter isDivisibleBy: aRule key]


  1. That's an interesting approach. I like your use of #detect: on an array of multiples and your use of #assert:

    I guess only TDD purists would consider this minimal though ;-)

  2. Squeak also as Number>>isDivisibleBy: which can make the code a bit cleaner but I think is Squeak specific.