Class: MusicalSpec::Note

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/musical_spec/note.rb

Overview

Uses scientific notation, e.g. C4 is middle C.

Constant Summary collapse

SCALE_PROGRESSION =
%w(C D E F G A B)

Instance Method Summary collapse

Constructor Details

#initialize(desired_note_string = nil) ⇒ Note

Takes 1 optional argument, a note string like “C4”.



9
10
11
# File 'lib/musical_spec/note.rb', line 9

def initialize(desired_note_string = nil)
  self.note = desired_note_string || LOWEST_NOTE.to_s
end

Instance Method Details

#higher!Object

Increase the pitch, handling octave changes. Will not go above MusicalSpec::HIGHEST_NOTE.



29
30
31
32
33
34
35
36
37
38
# File 'lib/musical_spec/note.rb', line 29

def higher!
  if below_highest_note?
    if @letter == SCALE_PROGRESSION.last
      @letter = SCALE_PROGRESSION.first
      @octave += 1
    else
      @letter = SCALE_PROGRESSION[SCALE_PROGRESSION.index(@letter) + 1]
    end
  end
end

#lower!Object

Decrease the pitch, handling octave changes. Will not go below MusicalSpec::LOWEST_NOTE.



42
43
44
45
46
47
48
49
50
51
# File 'lib/musical_spec/note.rb', line 42

def lower!
  if above_lowest_note?
    if @letter == SCALE_PROGRESSION.first
      @letter = SCALE_PROGRESSION.last
      @octave -= 1
    else
      @letter = SCALE_PROGRESSION[SCALE_PROGRESSION.index(@letter) - 1]
    end
  end
end

#note=(new_note) ⇒ Object

Set the note to a new one, e.g. ‘note.note = ’A5’‘



19
20
21
22
23
24
25
# File 'lib/musical_spec/note.rb', line 19

def note=(new_note)
  new_letter, new_octave = new_note.split('')
  @letter = new_letter
  @octave = new_octave.to_i

  to_s
end

#to_sObject

A string like “C4”.



14
15
16
# File 'lib/musical_spec/note.rb', line 14

def to_s
  "#{letter}#{octave}"
end