Sha256: 7114915169c0ebca75edcc9aba57c61e0870ccd5d6f9bc13884935f2de95c0ea

Contents?: true

Size: 1.14 KB

Versions: 8

Compression:

Stored size: 1.14 KB

Contents

# frozen_string_literal: true

# The Octave identifier is a number used in scientific pitch notation.
class HeadMusic::Octave
  include Comparable

  DEFAULT = 4

  def self.get(identifier)
    from_number(identifier) || from_name(identifier) || default
  end

  def self.from_number(identifier)
    return nil unless identifier.to_s == identifier.to_i.to_s
    return nil unless (-2..12).cover?(identifier.to_i)

    @octaves ||= {}
    @octaves[identifier.to_i] ||= new(identifier.to_i)
  end

  def self.from_name(string)
    return unless string.to_s.match?(HeadMusic::Spelling::MATCHER)

    _letter, _sign, octave_string = string.to_s.match(HeadMusic::Spelling::MATCHER).captures
    @octaves ||= {}
    @octaves[octave_string.to_i] ||= new(octave_string.to_i) if octave_string
  end

  def self.default
    @octaves[DEFAULT] ||= new(DEFAULT)
  end

  attr_reader :number

  delegate :to_i, :to_s, to: :number

  def initialize(number)
    @number = number
  end

  def <=>(other)
    to_i <=> other.to_i
  end

  def +(other)
    self.class.get(to_i + other.to_i)
  end

  def -(other)
    self.class.get(to_i - other.to_i)
  end

  private_class_method :new
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
head_music-0.26.2 lib/head_music/octave.rb
head_music-0.26.1 lib/head_music/octave.rb
head_music-0.26.0 lib/head_music/octave.rb
head_music-0.25.0 lib/head_music/octave.rb
head_music-0.24.5 lib/head_music/octave.rb
head_music-0.24.4 lib/head_music/octave.rb
head_music-0.24.3 lib/head_music/octave.rb
head_music-0.24.2 lib/head_music/octave.rb