I also summarized Expression used for FizzBuzz problem.

** Step 1 ** Output numbers from 1 to 100 to the terminal

** Step 2 ** When it is "multiple of 3", Fizz is a character string instead of a number. Similarly for "multiples of 5", Buzz

** Step 3 ** Output as FizzBuzz when it is a multiple of 3 and 5, which is a multiple of 15.

`Template`

```
def fizz_buzz
#Contents of processing
end
fizz_buzz
```

**step 1**
`Output numbers from 1 to 100 to the terminal`

`Output numbers from 1 to 100 to the terminal`

```
def fizz_buzz
num = 1
# num =Contents of processing starting from 1
while num <= 100 do #As long as the boolean value is true, the following processing continues
puts num #Output numerical value
num = num + 1 #To boolean value+1
end
#Contents of processing
end
fizz_buzz
```

** Step 2 **
`When it is a multiple of 3, use a character string instead of a number. `

Buzz` for" multiples of 5 "

`When it is "multiple of 3", it is output as Fizz as a character string, and when it is "multiple of 5", it is output as Buzz.`

```
def fizz_buzz
num = 1
# num =Contents of processing starting from 1
while num <= 100 do #As long as the boolean value is true, the following processing continues
if num % 3 == 0 #When the remainder divided by 3 is 0
puts "Fizz"
elsif num % 5 == 0 #When the remainder after dividing by 5 is 0
puts "Buzz"
else #At other times
puts num #Numerical values that do not correspond to the above multiples of 3 and 5 are output as they are.
end
num = num + 1 #To boolean value+1
end
#Contents of processing
end
fizz_buzz
```

** Step 3 **
`FizzBuzz and output when it is a multiple of 3 and 5, which is a multiple of 15.`

`Added conditional expression for "multiples of 15 (multiples of 3 and 5)"`

```
def fizz_buzz
num = 1
# num =Contents of processing starting from 1
while (num <= 100) do #As long as the boolean value is true, the following processing continues
if num % 15 == 0 #When it is a multiple of 15
puts "FizzBuzz"
elsif (num % 3) == 0 #When the remainder divided by 3 is 0
puts "Fizz"
elsif (num % 5) == 0 #When the remainder after dividing by 5 is 0
puts "Buzz"
else #At other times
puts num #Numerical values that do not correspond to multiples of 3, 5, and 15 above are output as they are.
end
num = num + 1 #To boolean value+1
end
#Contents of processing
end
fizz_buzz
```

Notes If you add it below, the above conditional expression "is it a multiple of 3" or "is it a multiple of 5" becomes true and is displayed as Fizz or Buzz.

From the above points, add a condition to output FizzBuzz when it is a "multiple of 15" at the beginning of the if statement.

- Alternative conditional expression "when it is a multiple of 15"
- The ones mentioned above are
`num% 15 == 0`

- Can be replaced with
`num% 3 == 0 && num% 5 == 0`

.

Recommended Posts