Last active
December 22, 2015 23:29
-
-
Save billgathen/6546668 to your computer and use it in GitHub Desktop.
Functional FizzBuzz. I've been reading the fantastic "Functional JavaScript" (http://functionaljavascript.com) and thought I'd try some Ruby in that style.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
module FizzBuzz | |
def self.generate last_num | |
1.upto(last_num).map do |n| | |
if n % 15 == 0 | |
'FizzBuzz' | |
elsif n % 5 == 0 | |
'Buzz' | |
elsif n % 3 == 0 | |
'Fizz' | |
else | |
n.to_s | |
end | |
end | |
end | |
def self.as_text last_num | |
generate(last_num).join(' ') | |
end | |
def self.as_json last_num | |
generate(last_num).to_json | |
end | |
def self.as_html last_num | |
<<EOHTML | |
<!DOCTYPE HTML> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title></title> | |
</head> | |
<body> | |
<ul> | |
#{generate(last_num).map{ |n| " <li>#{n}</li>" }.join("\n")} | |
</ul> | |
</body> | |
</html> | |
EOHTML | |
end | |
end | |
if __FILE__ == $0 | |
puts FizzBuzz.generate(15) | |
puts FizzBuzz.as_text(15) | |
puts FizzBuzz.as_json(15) | |
puts FizzBuzz.as_html(15) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment