Skip to content

Instantly share code, notes, and snippets.

@gouf
Last active May 22, 2024 19:59
Show Gist options
  • Save gouf/4cb98e8bc6ecf156dd48b86e0497b089 to your computer and use it in GitHub Desktop.
Save gouf/4cb98e8bc6ecf156dd48b86e0497b089 to your computer and use it in GitHub Desktop.
Hash 採用縛りで FizzBuzz
# Hash を用いて FizzBuzz 問題を解くクラス
# 15, 5, 3 の余りを Hash の key として登録しておき、FizzBuzz の解を得る
class FizzBuzz
attr_reader :hash
def initialize
# INFO: Hash instance method Hash#default_proc
# https://docs.ruby-lang.org/ja/latest/method/Hash/i/default_proc.html
hash =
Hash.new do |hash, key|
![3, 5, 0].include?(key)? key : hash[key]
end
hash.merge!({
3 => 'Fizz',
5 => 'Buzz',
0 => 'FizzBuzz'
})
@hash = hash
end
def solve
1.upto(100).map do |i|
# こっちでも OK
# ret = hash[i.modulo(15)] || hash[i.modulo(5)] || hash[i.modulo(3)]
# ret.is_a?(String)? ret : i.to_s
[15, 5, 3].map { i.modulo(_1) }
.map { hash[_1] }
.compact
.first
.then { _1.is_a?(String)? _1 : i.to_s }
end
end
end
puts FizzBuzz.new.solve
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment