Ruby Debugging Select Blocks
Debugging select is easy because the only thing you need to know is whether the predicate was true for a particular element. For example, a select filter that only keeps even numbers (number % 2== 0) could be debugged like this:
The predicate is false for number 1 The predicate is true for number 2 The predicate is false for number 3 The predicate is true for number 4 The predicate is false for number 5 => [2, 4]
Here, you can see that only the numbers for which the predicate was true ended up in the answer ([2,4]).
FizzBuzz
This program is used as a programming question. Write a program to go through a list of integers 1..N. If the number is divisible by 2, print “fizz”; if it is divisible by 3, print “buzz”; if it is divisible by 2 and 3, print “fizzbuzz”; otherwise, print the number. The input can be modeled as a range: (1..15).
The output should look like this:
That gives us the following:
That is close, but we didn’t address the buzz:
That gives us the following:
That’s close, but the fizzbuzz examples didn’t happen at 6 and 12. Let’s add in another clause. To be divisible by 2 and 3 implies that it must be divisible by 6:
This yielded the same result as the previous attempt. A closer inspection of the code suggests that if the number is divisible by 6, it will always be even and will be caught by the n%2==0 clause. However, if we catch the n%6==0 clause first, what happens?
That yields the following:
To print it, just do the following:
comments powered by Disqus