I tried the second solution and got an error "no implicit conversion of Fixnum into String" when using rails c with Pry; and NoMethodError: undefined method 'blank?' for String:Class when using irb:
[email protected]:~/paul$ irb
2.3.1 :001 > 1.upto(100) do |i|
2.3.1 :002 > str = ""
2.3.1 :004 > str += "Fizz" if i % 3 == 0
2.3.1 :005?> str += "Buzz" if i % 5 == 0
2.3.1 :006?> str += i if str.blank?
2.3.1 :008 > puts str
2.3.1 :009?> end
NoMethodError: undefined method `blank?' for "":String
from (irb):6:in `block in irb_binding'
from (irb):1:in `upto'
What am I doing wrong?
Oh you know what, I probably had access to ActiveSupport while I was doing that.
Add this line at the beginning if you have the active_support gem installed.
The blank? method doesn't come from Ruby but most of my work being in Rails I'm so used to having it around. :)
Great episode Chris, would love to see more like this!
If anyone else is interested, a cool site to work on problems similar to FizzBuzz is https://www.codewars.com. I try to do one a week (Although it's been quite some time since my last one).
Okay I'm hitting an error and I understand what it's saying but I'm more confused as to why it's happening.
`def fizzbuzz(start_num, end_num)
start_num.upto(end_num) do |n|
str = ""
str += "fizz" if n % 3 == 0
str += "buzz" if n % 5 == 0
str += n if str.empty?
And when I run it....
`assessment_109.rb:7:in `+': no implicit conversion of Fixnum into String (TypeError)`
Changing the += to a = in the last line works (and since it's an empty string, it outputs the same)
Did anyone else run into this?
Is this just a typo that I'm over thinking or am I completely missing something here?
I hope you do more of these Chris. It's always great to see different ways people solve coding challenges.
I tried to solve the problem without defining empty string. But the result might be a bit more complicated.
1.upto(100) do |i|
str = 'fizz' if (i % 3).zero?
str = str ? 'fizzbuzz' : 'buzz' if (i % 5).zero?
str = i unless str
It's helpful to learn how to write clean and clear code!
Hi Chris, really like this example. I have a couple of pieces of feedback since I tried to run it and encountered issues. Line 19 needs to be str = i instead of str += i. Since str is started as a string, I get "no implicit conversion of Integer into String" when I try to add the i. Also, str.blank? works if you are in an ActiveSupport context. Otherwise, str.empty? is available.
Join 31,575+ developers who get early access to new screencasts, articles, guides, updates, and more.