On my quest to learn Ruby I figured exploring the proper usage of different data-structures would be invaluable, including strings, arrays and hashes.
I decided to build a hash containing the numbers 1 till 100 inclusive. These hashes would contain:
- Whether the number is prime
- What it's FizzBuzz output would be
- The n-th Fibonacci number.
In the end the number itself turned into a value as well. I intended the number to be the key and the other 3 values to be a hash of that key but it got too complicated.
As a side effect my project got quite bulky and should probably be split up. Somehow. My gut tells me I should move the FizzBuzz and Fibonacci parts to their own module and import them like I did with the already existing prime
module.
On top of that, I got a couple of concerns:
- Is
output += "Fizz"
the idiomatic way of adding a string to a string? - Is my usage of the hash proper or is it not supposed to be used like this?
- Did I adhere to variable naming rules?
- How is the general readability?
Code:
require 'prime'
class Fibonacci
def initialize(max)
@max = max
@list = [1, 1, 2]
for i in 3..@max do
@list << @list[i-2] + @list[i-1]
end
end
def get_nth(n)
return @list[n]
end
end
numbers = []
def fizzbuzz(number)
output = ""
if (number % 3 == 0)
output += "Fizz"
end
if (number % 5 == 0)
output += "Buzz"
end
if output == ""
output = number
end
return output
end
Fib = Fibonacci.new(100)
for number in 1..100 do
hash = {
:Number => number,
:FizzBuzz => fizzbuzz(number),
:Prime => Prime.instance.prime?(number),
:Fibonacci => Fib.get_nth(number)
}
numbers << hash
end
The results can be called like this:
Primes:
numbers.each { |number| puts number[:Number], number[:Prime] }
FizzBuzz:
numbers.each { |number| puts number[:FizzBuzz] }
Fibonacci:
numbers.each { |number| puts number[:Number], number[:Fibonacci] }