Ruby: FizzBuzz not working as expected - ruby

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)

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"]

Using `map` to solve 'FizzBuzz'

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.

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.

Fizz Buzz in Ruby for dummies

Spoiler alert: I am a true novice. Tasked with figuring out fizz buzz in
ruby for a class and while I have found more than a few versions of code
that solve the problem, my understanding is so rudimentary that I cannot
figure out how these examples truly work.
First question(refer to spoiler alert if you laugh out loud at this):
How do i print out numbers one through 100 in Ruby?
Second question: can 'if else" be used to solve this? My failed code is
below(attachment has screen shot):
puts('Lets play fizzbuzz')
print('enter a number: ')
number = gets()
puts(number)
if number == % 3
puts ('fizz')
elsif number == % 5
puts ('buzz')
elsif number == %15
puts ('fizzbuzz')
end
Thanks,
Thats ok being a novice, we all have to start somewhere right? Ruby is lovely as it get us to use blocks all the time, so to count to 100 you can use several methods on fixnum, look at the docs for more. Here is one example which might help you;
1.upto 100 do |number|
puts number
end
For your second question maybe take a quick look at the small implementation i whipped up for you, it hopefully might help you understand this problem:
1.upto 100 do |i|
string = ""
string += "Fizz" if i % 3 == 0
string += "Buzz" if i % 5 == 0
puts "#{i} = #{string}"
end
First question: this problem has several solutions. For example,
10.times { |i| puts i+1 }
For true novice: https://github.com/bbatsov/ruby-style-guide
another method that can be helpful :
puts (1..100).map {|i|
f = i % 3 == 0 ? 'Fizz' : nil
b = i % 5 == 0 ? 'Buzz' : nil
f || b ? "#{ f }#{ b }" : i
}
As a one liner
(1..100).map { |i| (i % 15).zero? ? 'FizzBuzz' : (i % 3).zero? ? 'Fizz' : (i % 5).zero? ? 'Buzz' : i }
In Regards to your failed code, your conditional statements should be like this:
if number % 3 == 0
puts "Fizz"
end
if number % 5 == 0
puts "Buzz"
end
You don't want the last elsif statement because it will never get executed
(if a number is not divisible by 3 or divisible by 5, then it is certainly not divisible by 15)
Adjust for this by changing the second elsif to simply and if and if the number is divisble by 5 and not by 3, then Fizz will not be outputted but Buzz Will be
I'm just showing you how to correct your code, but as others have pointed out, there are far more elegant solutions in Ruby.
Not the most beautiful way to write it but good for beginners and for readability.
def fizzbuzz(n)
(1..n).each do |i|
if i % 3 == 0 && i % 5 == 0
puts 'fizzbuzz'
elsif i % 3 == 0
puts 'fizz'
elsif i % 5 == 0
puts 'buzz'
else
puts i
end
end
end
fizzbuzz(100)
1.upto(100).each do |x| # Question #1 The 'upto' method here takes is
# what you would use to count in a range.
if (x % 3 == 0) && (x % 5 == 0)
puts " Fizzbuzz"
elsif x % 3 == 0
puts " Fizz"
elsif x % 5 == 0
puts " Buzz"
else
puts x
end
end
Question #2 Yes you can but I would look for a more elegant way to write this as a part of a definition like
def fizzbuzz(last_number)
1.upto(last_number).each do |x|
if (x % 3 == 0) && (x % 5 == 0)
puts " Fizzbuzz"
elsif x % 3 == 0
puts " Fizz"
elsif x % 5 == 0
puts " Buzz"
else
puts x
end
end
end
This is the answer that helped me to understand that no variables are being created with the .each method. Sorry about my indenting. Still learning how to use Stackoverflow text editing.
As for a more complex solution, that's one way you could build
a simple DSL for quickly modifying the FizzBuzz programme (adding new divisors with their own keywords)
class FizzBuzzer
# #return [Hash{String, Symbol => Integer}]
attr_reader :keywords
# #param keywords [Hash{String, Symbol => Integer}]
def initialize(keywords)
#keywords = keywords
end
# #param range [Range]
# #return [void]
def call(range)
range.each do |num|
msg = ''
#keywords.each do |name, divisor|
msg << name.to_s if (num % divisor).zero?
end
msg = num if msg.empty?
puts msg
end
puts
end
end
# create a fizz buzzer with custom keywords for divisors
CLASSIC_FIZZ_BUZZER = FizzBuzzer.new Fizz: 3, Buzz: 5
# print for a particular range
CLASSIC_FIZZ_BUZZER.call(1..25)
# you can easily define an extended fizz buzzer
EXTENDED_FIZZ_BUZZER = FizzBuzzer.new Fizz: 3, Buzz: 5, Bazz: 7, Fuzz: 11 # print 'Fuzz' when divisible by 11
EXTENDED_FIZZ_BUZZER.call(1..25)
Here's a quite elegant solution.
(1..100).each do |num|
msg = ''
msg << 'Fizz' if (num % 3).zero?
msg << 'Buzz' if (num % 5).zero?
msg = num if msg.empty?
puts(msg)
end
It can be even more compact
(1..100).each do |num|
(msg ||= '') << 'Fizz' if (num % 3).zero?
(msg ||= '') << 'Buzz' if (num % 5).zero?
puts msg || num
end
FizzBuzz
(1..100).each do |num|
if num % 3 == 0 && num % 5 == 0
puts "#{num}. FIZZBUZZ!"
elsif num % 3 == 0
puts "#{num}. FIZZ!"
elsif num % 5 == 0
puts "#{num}. BUZZ!"
else
puts "#{num}."
end
end
First question:
for i in 1..100
puts i
end
Here is my most "idiomatic ruby" solution:
class FizzBuzz
def perform
iterate_to(100) do |num,out|
out += "Fizz" if num.divisable_by?(3)
out += "Buzz" if num.divisable_by?(5)
out || num
end
end
def iterate_to(max)
(1..max).each do |num|
puts yield num,nil
end
end
end
class Fixnum
def divisable_by?(num)
self % num == 0
end
end
class NilClass
def +(other)
other
end
end
FizzBuzz.new.perform
And it works:
https://gist.github.com/galori/47db94ecb822de2ac17c

Resources