k-tokitoh

2019-06-02

Ruby手習い(正規表現)

アウトプットのネタに困ったらこれ!?Ruby 初心者向けのプログラミング問題を集めてみた(全 10 問) - give IT a try

上記記事のカラオケマシーン問題。

自分で書いたコード

class KaraokeMachine
  KEYS = %w(C C# D D# E F F# G G# A A# B)

  def initialize(melody)
    @melody = melody
  end

  def transpose(diff)
    @melody.gsub(/[A-G]#?/) {|l| KEYS[(KEYS.index(l)+diff)%12]}
  end
end

出題者による回答例

class KaraokeMachine
  SCALE = %w(C C# D D# E F F# G G# A A# B).freeze

  def initialize(melody)
    @melody = melody
  end

  def transpose(amount)
    converter = [SCALE, SCALE.rotate(amount)].transpose.to_h
    @melody.gsub(/[A-G]#?/, converter)
  end
end

「CodeIQ ベストコード発表会 ~最もエレガントにカラオケマシン問題を解いた挑戦者は誰だ!?~」を放送しました #sg_study - give IT a try

学んだこと