2

I'm trying to write a looping fizzbuzz code that ends with the user_input's number. So far the code works, but it loops the number of times you put in for the user_input, not end at the user_input's limit. For example, if I type in 25, it will loop 25 times, and not end at 25. How do I set the parameters/range?

Here is my code:

puts("Please select a number that is at least 25. This is the limit for the fizzbuzz game.")

user_input = gets().chomp().to_i 

if
user_input < 25 
    puts("Please select a larger number.")

else 
user_input >= 25 
    user_input = user_input

    counter = 1

    while counter < user_input 
        puts(counter)
        counter = counter + 1

    (1..user_input).step 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 
end 
Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
  • 2
    You are using two loops, when you need only one. Remove the `step` loop, and replace all references to `i` with `counter`. That should get you a `step` (hehe) closer to the solution. (Check your `<`; also, note that `user_input >= 25` is twice-useless, because it is not used by anything and because even if you wrote `elsif` instead of `else`, it would be always true when evaluated.) Alternately (and better), do everything with a range and drop the `while`. – Amadan Dec 24 '14 at 04:38
  • Not a fan of while statements, I would use 1.upto(user_input) and implement a case inside it – neo Dec 24 '14 at 04:59

1 Answers1

2
  • It is optional to write () when you send no parameters to a method and usually discouraged
  • You shouldn't use else user_input >= 25, else is enough
  • user_input = user_input is totally useless line
  • while cycles with counters isn't the way rubists code, prefer iterators. Moreover, you shouldn't have while here at all
puts 'Please select a number that is at least 25. This is the limit for the fizzbuzz game.'    
user_input = gets.chomp.to_i
if user_input < 25
  puts 'Please select a larger number.'
else
  1.upto(user_input) 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

optionally, you can use case-when instead of multiple elsif statements:

puts 'Please select a number that is at least 25. This is the limit for the fizzbuzz game.'
user_input = gets.chomp.to_i
if user_input < 25
  puts 'Please select a larger number.'
else
  1.upto(user_input) do |i|
    case
    when [3, 5].all? { |n| i % n == 0 }; puts 'fizzbuzz'
    when i % 3 == 0; puts 'fizz'
    when i % 5 == 0; puts 'buzz'
    else; puts i
    end
  end
end
Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72