Using `map` to solve 'FizzBuzz' - ruby

I tired to use map to solve fizzbuzz.
def fizzbuzz(n)
array =(1..n).to_a
array.map{|x|
if x % 3 == 0 && x % 5 == 0
x = 'FizzBuzz'
elsif x % 3 == 0
x = 'Fizz'
elsif x % 5 == 0
x = 'Buzz'
end
}
array
end
Somehow, it doesn't work. Do you know what's wrong?

Method map does not change the original array. Use the bang version map! instead.

Using map! as suggested by #tmc and some other changes try:
def fizzbuzz(n)
array =(1..n).to_a
array.map!{|x|
if x % 3 == 0 && x % 5 == 0
x = 'FizzBuzz'
elsif x % 3 == 0
x = 'Fizz'
elsif x % 5 == 0
x = 'Buzz'
else
x = x
end
}
p array
end
fizzbuzz(10) #=> [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz"]
As you can see I've added a call to the method fizzbuzz with an argument of 10 which you can change. And I've used p to inspect the array as well as a final else statement.

Related

Ruby FizzBuzz using arrays, my logic seems right but it is getting an error

FizzBuzz, a classic problem, returns all the numbers up to N with a slight twist. If a number is divisible by 3, it is replaced with "fizz". If it's divisible by 5, it's replaced with "buzz". If it's divisible by both, it's replaced with "fizzbuzz"
I keep getting this Error message:
comparison of Fixnum with nil failed
Can someone explain this error message to me please? Also why is the code not working?
def fizz_buzz(n)
arr = (1..n).to_a
i = 0
while arr[i] < arr[n]
if i % 3 == 0 && i % 5 == 0
arr[i] = 'fizzbuzz'
elsif i % 3 == 0
arr[i] = 'fizz'
elsif i % 5 == 0
arr[i] = 'buzz'
else
arr[i] = i
i += 1
end
end
return arr
end
fizz_buzz(12)
Your conditions are just a bit off, give this a try:
def fizz_buzz(n)
arr = (1..n).to_a
i = 0
while i < n
if arr[i] % 3 == 0 && arr[i] % 5 == 0
arr[i] = 'fizzbuzz'
elsif arr[i] % 3 == 0
arr[i] = 'fizz'
elsif arr[i] % 5 == 0
arr[i] = 'buzz'
end
i+=1
end
return arr
end
Trying to access arr[n] puts you outside the bounds of the array which returns nil in Ruby.
You can update the code the ruby way, by using blocks and guards, I don't remember last time I used a while loop in ruby :)
Also, Array.new accepts a block as an argument which you can exploit to build your Array in a single step:
def fizz_buzz(n)
Array.new(n) do |index|
x = index + 1
case
when x % 3 == 0 && x % 5 == 0 then "fizzbuzz"
when x % 3 == 0 then "fizz"
when x % 5 == 0 then "buzz"
else x
end
end
end
Notice I used 1 as a base index and not 0, you can just remove x = index + 1 and replace x with index to have it working in a zero index base
A solution with a block instead of the while loop, and guards
def fizz_buzz(n)
arr = (1..n).to_a
0.upto(n - 1) do |i|
arr[i] = "fizzbuzz" and next if i % 3 == 0 && i % 5 == 0
arr[i] = "fizz" and next if i % 3 == 0
arr[i] = "buzz" if i % 5 == 0
end
arr
end
#brad-melanson beat me to the straight-forward answer to your question, so I'll share an answer which uses some common Ruby idioms (passing a range to the Array constructor and map), which simplify things, prevent you from having to do any iteration bookkeeping and prevent the possibility of off-by-one errors, out-of-bounds errors, etc.
def fizz_buzz(n)
Array(1..12).map do |n|
if n % 3 == 0 && n % 5 == 0
'fizzbuzz'
elsif n % 3 == 0
'fizz'
elsif n % 5 == 0
'buzz'
else
n
end
end
end
result = fizz_buzz 12
# result => [1, 2, "fizz", 4, "buzz", "fizz", 7, 8, "fizz", "buzz", 11, "fizz"]

Fizzbuzz switch statement

Long question but I think it is odd. I was playing around with ruby switch statements. Created a little fizzbuzz function to practice.
Initially created the code like this
def fizzbuzz(start_num, end_num)
fizzbuzz = []
(start_num..end_num).each do |x|
if x % 3 == 0 && x % 5 != 0
fizzbuzz << "fizz"
elsif x % 5 == 0 && x % 3 != 0
fizzbuzz << "buzz"
elsif (x % 3 == 0 && x % 5 == 0)
fizzbuzz << "fizzbuzz"
else
fizzbuzz << x.to_s
end
end
fizzbuzz
end
Works as expected. Then wanted to play with a switch statement. So I tried:
def fizzbuzz(start_num, end_num)
fizzbuzz = []
(start_num..end_num).each do |x|
case x
when x % 3 == 0
fizzbuzz << "fizz"
when x % 5 == 0
fizzbuzz << "buzz"
when (x % 3 == 0 && x % 5 == 0)
fizzbuzz << "fizzbuzz"
else
fizzbuzz << x.to_s
end
end
fizzbuzz
end
This time the code only prints out the number converted to a string. Then mistakenly I tried to add && to the end of every when statement like so
def fizzbuzz(start_num, end_num)
fizzbuzz = []
(start_num..end_num).each do |x|
case x
when x % 3 == 0 &&
fizzbuzz << "fizz"
when x % 5 == 0 &&
fizzbuzz << "buzz"
when (x % 3 == 0 && x % 5 == 0) &&
fizzbuzz << "fizzbuzz"
else
fizzbuzz << x.to_s
end
end
fizzbuzz
end
Interestingly this prints out the correct result. It is probably a trivial answer, but does anyone know why this is the case? It seems rather odd to me.
The when statements are doing a logical &&.
This has the side effect of concatenating your output when the condition is true.
The question you're actually asking, based on your comment, is what's going on with the when statements not seeming to work. The problem is that you wrote case x, which is evaluating x on-the-spot and comparing it to the when expressions.
Instead, use a "naked case", e.g.,
case
when (x % 3) == 0
# etc
Note also that this could be wrapped up a bit tighter, e.g.,
def fizzbuzz(start_num, end_num)
(start_num..end_num).collect do |x|
case
when (x % 3) == 0
"fizz"
when (x % 5) == 0
"buzz"
when (x % 3 == 0 && x % 5 == 0)
"fizzbuzz"
else
x.to_s
end
end
end
For the last piece of code, let's see one when condition in detail:
when x % 3 == 0 &&
fizzbuzz << "fizz"
Despite the indentation, it's equivalent to:
when x % 3 == 0 && fizzbuzz << "fizz"
Remember that && is short-circuit. The && expression returns its first argument if it is false. Otherwise, its second argument is evaluated and returned as the result.
So if x % 3 == 0 is false, then fizzbuzz << "fizz" is not executed. If x % 3 == 0 is true, fizzbuzz << "fizz" is executed. Exactly what is expected.

Refactor if/else statement - Ruby

I know there has to be a better way to write this. I try not to use if/else if possible, or at least cut them down, but I'm still a noob with Ruby so some refactoring help would be much appreciated.
def super_fizzbuzz(array)
array.map {|x|
if x % 15 == 0
"FizzBuzz"
elsif x % 3 == 0
"Fizz"
elsif x % 5 == 0
"Buzz"
else x
end}
end
I would do it like this:
def super_fizzbuzz(array)
array.map do |x|
case
when x % 15 == 0 then 'FizzBuzz'
when x % 3 == 0 then 'Fizz'
when x % 5 == 0 then 'Buzz'
else x
end
end
end
[spoilers]
There are several ways to do this classic problem... This way has no ifs/elses
(1..100).each do |x|
m3 = x.modulo(3) == 0
m5 = x.modulo(5) == 0
puts case
when (m3 and m5) then 'FizzBuzz'
when m3 then 'Fizz'
when m5 then 'Buzz'
else x
end
end
OR, if you prefer the if statements and small code blocks, this is a good refactoring of what you have
(1..100).each{|i|
x = ''
x += 'Fizz' if i%3==0
x += 'Buzz' if i%5==0
puts(x.empty? ? i : x);
}
I will do something like
array.map do |x|
[FizzBuzz, Fizz, Default].map do |fizzer|
fizzer.new(x).get
end.compact.first
end
class FizzBuzz
attr_reader :x
private :x
def initialize(x)
#x = x
end
def get
'FizzBuzz' if x % 15
end
end
class Fizz
attr_reader :x
private :x
def initialize(x)
#x = x
end
def get
'FizzBuzz' if x % 3
end
end
Default = Struct(:get)
...
That way you will split responsabilities and have each class responsible for only one thing.

Ruby: FizzBuzz not working as expected

I'm having trouble getting an IF statement to produce the results I think they should. I'm not sure why I cannot get the && ("and") conditional to work.
def fizzbuzz(n)
pool = []
(1..n).each do |x|
if x % 3 == 0
pool.push('Fizz')
elsif x % 5 == 0
pool.push('Buzz')
elsif x % 3 == 0 && x % 5 == 0
pool.push('FizzBuzz')
else
pool.push(x)
end
end
puts pool
end
fizzbuzz(10)
and they results
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
I'm not sure what I'm doing wrong here.
Try this instead:
def fizzbuzz(n)
pool = []
(1..n).each do |x|
if x % 3 == 0 && x % 5 == 0
pool.push('FizzBuzz')
elsif x % 5 == 0
pool.push('Buzz')
elsif x % 3 == 0
pool.push('Fizz')
else
pool.push(x)
end
end
puts pool
end
When you use if/elsif/elsif/else, it will execute only one of this conditions at time. If x % 3 == 0, then that's it, ruby will no longer enter any of those conditions, that's why fizzbuzz will never be printed.
The if/else if/else branching only executes one of the code blocks. If a condition is true, then the following block is executed and the program will skip to the end of the if/else statements.
Here is another working version, which is a bit cleaner, but as Tiago Farias said, you wont get the 'fizzbuzz' message printed in a range from [1..10], because you don't have a value which will have the rest 0 for both % 3 and % 5, the closest will be 15.
def fizzbuzz(n)
#pool = []
(1..n).each do |x|
send_no x
end
puts #pool
end
def send_no x
return #pool << 'fizzbuzz' if x % 3 == 0 && x % 5 == 0
return #pool << 'fizz' if x % 3 == 0
return #pool << 'buzz' if x % 5 == 0
#pool << x
end
fizzbuzz(10)

How can I DRY this series of conditional statements?

I often find myself checking multiple conditions. How can I cut down on the number of lines used to achieve the same effect?
def super_fizzbuzz(array)
final = []
for num in array
if num % 15 == 0
final << 'FizzBuzz'
elsif num % 5 == 0
final << 'Buzz'
elsif num % 3 == 0
final << 'Fizz'
else
final << num
end
end
final
end
def super_fizzbuzz(array)
array.map do |num|
a = []
a << 'Fizz' if num % 3 == 0
a << 'Buzz' if num % 5 == 0
a.empty? ? num : a.join()
end
end
def super_fizzbuzz(array)
final = []
array.each do |num|
num % 15 == 0 ? final << 'FizzBuzz' : num % 5 == 0 ? final << 'Buzz' : num % 3 == 0 ? final << 'Fizz' : final << num
end
final
end
But your way is more readable.
def super_fizzbuzz(array)
array.map do |num|
case 0
when num % 15 then "FizzBuzz"
when num % 5 then "Buzz"
when num % 3 then "Fizz"
else num
end
end
end
This is slightly more complex, but reduces number of explicit coded conditionals to 2:
FIZZBUZZ = { 3 => 'Fizz', 5 => 'Buzz' }
def super_fizzbuzz(array)
array.map do |num|
fbs = FIZZBUZZ.select do |divisor,cat|
num % divisor == 0
end.values
fbs.empty? ? num : fbs.join
end
end
There is always the danger when coding for DRY that you take things too far. In this case, with only two overlapping categories, I think the above is a little unwieldy. However, add another category or two:
FIZZBUZZ = { 3 => 'Fizz', 5 => 'Buzz', 7 => 'Boom', 11 => 'Whizz' }
and it starts to look smarter.
Quote:
I think Fizz-Buzz is "hard" for some programmers because (#1) it doesn't fit into any of the patterns that were given to them in school assignments, and (#2) it isn't possible to directly and simply represent the necessary tests, without duplication, in just about any commonly-used modern programming language.
Source: c2.com Wiki
Another way:
def super_fizzbuzz(arr)
arr.map do |e|
s = ''
s << 'Fizz' if (e%3).zero?
s << 'Buzz' if (e%5).zero?
s = e if s.empty?
s
end
end
super_fizzbuzz [9, 25, 225, 31]
#=> ["Fizz", "Buzz", "FizzBuzz", 31]

Resources