## FOOBAR in Ruby

Here’s how I solved the FOOBAR challenge using Ruby and why I did it this way. If you’re unfamiliar with this challenge, you’re goal is to have the computer print out a list of numbers from 1 to (whatever). When the number is divisible by 3, replace that number with FOO and when the number is divisible by 5, replace that number with BAR. When the number is divisible by both 3 and 5, replace that number with FOOBAR.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
puts "How many items do you want to see?" items = gets.chomp.to_i list = [] (1..items).each do |n| if n % 3 == 0 && n % 5 == 0 list << "FOOBAR" elsif n % 3 == 0 list << "FOO" elsif n % 5 == 0 list << "BAR" else list << n end end puts list |

In short, this program creates a new list with the FOOBAR results and stores it into an empty array. We then display the array (list) onto the console. Nice and simple!

- I start with asking the user how many items (numbers) they want to see.
- Then, I convert the answer into an integer and store it in the
*items*variable. The reason we convert to an integer is because the gets.chomp method converts whatever is inputed into a string. - Next, I create an empty array and assign it to the
*list*variable. - On line 5 I start the loop at number 1 and end it at whatever number the user entered, which is stored in the
*items*variable. - Line 6 uses the remainder operator (%) to see if n (each number in the loop) is divisible by both 3
**and**5. The % operator divides the two numbers and returns the remainder. If there is no remainder then we know the number on the left is divisible by the number on the right. For example 9 % 3 will return 0 because 3 goes into 9, 3 times and there’s no remainder. But if you try 5 % 3 then you get 2 as your remainder, because 3 goes into 5 once and there’s 2 left over.- The && operator checks to see if both statements are true and if they are, then do the next statement. But if either one is not true, then move on to the next condition.

- When a condition is true, notice how the result gets added to the array. Ruby calls << the append operator and it does exactly what it looks like; takes the element on the right and stores it into the variable on the left (our empty array).
- When line 6 is false, then line 8 checks to see if n is divisible by 3.
- When line 8 is false then line 10 checks to see if n is divisible by 5.
- Line 13 happens when lines 6, 8, and 10 are all false. This stores n (each number in loop not divisible by 3
**or**5) into the array. - Finally, we display the array onto the console by simply writing puts list

Please post any questions or comments below!

(Visited 280 times, 1 visits today)