Skip to content

Instantly share code, notes, and snippets.

@billgathen
Last active December 22, 2015 23:29
Show Gist options
  • Save billgathen/6546668 to your computer and use it in GitHub Desktop.
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.
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