In this article, I've summarized the FizzBuzz issue!
You may have seen this problem very early in your learning of programming.
The FizzBuzz problem is not too difficult for beginners and is an effective learning material for programming.
I will do my best to make it easy for beginners to understand, so please stay with me until the end!
The FizzBuzz problem in programming is "Fizz" if you enter a number that can be divided by 3, "Buzz" if you enter a number that can be divided by 5, or a number that can be divided by both (that is, divide by 15). It's a problem of writing a program that responds with "FizzBuzz" when you enter a number that can be used.
It is often mentioned when you buy an introductory reference book for Ruby, so many of you may say that you have actually solved it.
First, let's take a look at the completed code.
FizzBuzz.rb
def FizzBuzz(n)
if n % 15 == 0
'FizzBuzz'
elsif n % 3 == 0
'Fizz'
elsif n % 5 == 0
'Buzz'
else
n.to_s
end
end
First, when n is divided by 15, too much is 0, that is, if a number that can be divided by 15 is input, it is instructed to return'FizzBuzz'.
Next, if you enter a number that can be divided by 3, it will return'Fizz', and if you enter a number that can be divided by 5, it will return'Buzz'.
Finally, if any other number is entered, it is instructed to convert that number to a string and return it.
Let's actually run this program.
First, under the method I just wrote, I will write an instruction using the method.
FizzBuzz.rb
def FizzBuzz(n)
if n % 15 == 0
'FizzBuzz'
elsif n % 3 == 0
'Fizz'
elsif n % 5 == 0
'Buzz'
else
n.to_s
end
end
FizzBuzz(1)
FizzBuzz(3)
FizzBuzz(4)
FizzBuzz(5)
FizzBuzz(10)
FizzBuzz(15)
Then, give the following command to the terminal.
$ ruby lib/FizzBuzz.rb
This is a command to execute a file called FizzBuzz.rb directly under a directory (folder) called lib.
When you actually run it, you should see the following results.
1
Fizz
4
Buzz
10
FizzBuzz
If you get the same result, you will be successful!
The FizzBuzz question is a beginner's entry-level programming exercise.
Write the program so that if you enter a multiple of 3, Fizz will be output, if it is 5, Buzz will be output, and if it is a multiple of both, FizzBuzz will be output.
How was it? I would appreciate it if you could let me know if there are any points that are difficult to understand!
It will be a material for rewriting this article, and it will lead to my own growth, so I would love to hear from you!
Recommended Posts