Fizz Buzz in Ruby for dummies

2020-07-24 04:01发布

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,

标签: ruby fizzbuzz
9条回答
叛逆
2楼-- · 2020-07-24 04:08

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)
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-07-24 04:08

First question:

for i in 1..100
    puts i
end
查看更多
啃猪蹄的小仙女
4楼-- · 2020-07-24 04:10

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
    }
查看更多
对你真心纯属浪费
5楼-- · 2020-07-24 04:14

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

查看更多
甜甜的少女心
6楼-- · 2020-07-24 04:18

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

查看更多
不美不萌又怎样
7楼-- · 2020-07-24 04:25

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
查看更多
登录 后发表回答