As a study of Ruby, I solved the ** FizzBuzz problem ** using ** while ** and ** each **. There are other ways to solve it, but this time I tried to solve the problem with ** while **, which I personally use less frequently, and ** each **, which I often use.
** (Added on 2020.1.13) I also practiced the method using the upto method and arguments. ** **
--Practice --Problem --Answer (while) --Answer (each) --Answer (up to)
--Supplement
--Summary
--References
Output the numbers
1 ~ 100
to the terminal.
【conditions】
--Output as " Fizz "
when the value is a multiple of 3
--Output as " Buzz "
when the value is a multiple of 5.
--Output as " FizzBuzz "
when the values are multiples of 3 and 5.
def fizz_buzz
num = 0
while (num <= 100) do #Conditions to repeat up to 100
num += 1 #Add 1 each time you repeat
if (num % 15) == 0 #When it is a multiple of 15
p 'FizzBuzz'
elsif (num % 3) == 0 #When it is a multiple of 3
p 'Fizz'
elsif (num % 5) == 0 #When it is a multiple of 5
p 'Buzz'
else #At other times
p num
end
end
end
fizz_buzz
def fizz_buzz
(1..100).each do |num| # 1~Up to 100
if (num % 15) == 0 #When it is a multiple of 15
p 'FizzBuzz'
elsif (num % 3) == 0 #When it is a multiple of 3
p 'Fizz'
elsif (num % 5) == 0 #When it is a multiple of 5
p 'Buzz'
else #At other times
p num
end
end
end
fizz_buzz
def fizz_buzz
1.upto(100) do |num| #From 1 to 100
if num % 15 == 0
p 'FizzBuzz'
elsif num % 3 == 0
p 'Fizz'
elsif num % 5 == 0
p 'Buzz'
else
p num
end
end
end
fizz_buzz
I wrote a program hoping to create a pattern of 1 to any number
instead of 1 to 100
.
The method doesn't change much, it just iterates ** up to the value specified by the argument **.
def fizz_buzz(max_num)
1.upto(max_num) do |num| #1 to the number specified by the argument (arbitrary number)
if num % 15 == 0
p 'FizzBuzz'
elsif num % 3 == 0
p 'Fizz'
elsif num % 5 == 0
p 'Buzz'
else
p num
end
end
end
p 'How many do you count?'
num = gets.to_i
fizz_buzz(num)
Outputs
" FizzBuzz "
when the values are multiples of 3 and 5.
num % 3 == 0 && num % 5 == 0
The answer says (num% 15) == 0
, but you can replace it as above.
** Reasons to write the condition of multiples of 3 or multiples of 5 (multiples of 15) ** first
As you can see in the problem statement, ** "multiples of 3 and 5" is FizzBuzz **, so it must be a multiple of ** 3 and a multiple of 5 (a multiple of 15) **. If you write this condition at the end, the conditions of ** "multiple of 3" ** and ** "multiple of 5" ** will be evaluated before that, so add ** multiple of 15 ** at the beginning. doing.
--There are other ways to solve the FizzBuzz problem, and you can solve other than the ones mentioned above. --When there is a condition like this time, it will not be evaluated unless ** a multiple of 15 ** is added first.
-IT Glossary (FizzBuzz Problem) that makes you feel like "I understand" but "I don't understand"
-Ruby 3.0.0 Reference Manual (Integer # upto)
Recommended Posts