Class: MusicalSpec::Note
- Inherits:
-
Object
- Object
- MusicalSpec::Note
- 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 Attribute Summary collapse
-
#letter ⇒ Object
readonly
Returns the value of attribute letter.
-
#octave ⇒ Object
readonly
Returns the value of attribute octave.
Instance Method Summary collapse
- #<=>(other_note) ⇒ Object
-
#initialize(desired_note_string = nil) ⇒ Note
constructor
Takes 1 optional argument, a note string like “C4”.
-
#next! ⇒ Object
Increase the pitch, handling octave changes.
-
#note=(new_note) ⇒ Object
Set the note to a new one, e.g.
-
#prev! ⇒ Object
Decrease the pitch, handling octave changes.
-
#to_s ⇒ Object
A string like “C4”.
Constructor Details
#initialize(desired_note_string = nil) ⇒ Note
Takes 1 optional argument, a note string like “C4”.
9 10 11 12 13 14 15 |
# File 'lib/musical_spec/note.rb', line 9 def initialize(desired_note_string = nil) if desired_note_string.nil? self.note = LOWEST_NOTE.to_s else self.note = desired_note_string end end |
Instance Attribute Details
#letter ⇒ Object (readonly)
Returns the value of attribute letter.
17 18 19 |
# File 'lib/musical_spec/note.rb', line 17 def letter @letter end |
#octave ⇒ Object (readonly)
Returns the value of attribute octave.
17 18 19 |
# File 'lib/musical_spec/note.rb', line 17 def octave @octave end |
Instance Method Details
#<=>(other_note) ⇒ Object
63 64 65 66 67 68 69 70 71 |
# File 'lib/musical_spec/note.rb', line 63 def <=>(other_note) other_letter = other_note.letter other_octave = other_note.octave if octave == other_octave SCALE_PROGRESSION.index(letter) <=> SCALE_PROGRESSION.index(other_letter) else octave <=> other_octave end end |
#next! ⇒ Object
Increase the pitch, handling octave changes. Will not go above MusicalSpec::HIGHEST_NOTE.
35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/musical_spec/note.rb', line 35 def next! if self != HIGHEST_NOTE if @letter == 'B' @letter = 'C' @octave += 1 elsif @letter == 'G' @letter = 'A' else @letter.next! end end end |
#note=(new_note) ⇒ Object
Set the note to a new one, e.g. ‘note.note = ’A5’‘
25 26 27 28 29 30 31 |
# File 'lib/musical_spec/note.rb', line 25 def note=(new_note) new_letter, new_octave = new_note.split('') @letter = new_letter @octave = new_octave.to_i to_s end |
#prev! ⇒ Object
Decrease the pitch, handling octave changes. Will not go below MusicalSpec::LOWEST_NOTE.
50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/musical_spec/note.rb', line 50 def prev! if self != LOWEST_NOTE if @letter == 'C' @letter = 'B' @octave -= 1 elsif @letter == 'A' @letter = 'G' else @letter = (@letter.ord - 1).chr end end end |
#to_s ⇒ Object
A string like “C4”.
20 21 22 |
# File 'lib/musical_spec/note.rb', line 20 def to_s "#{letter}#{octave}" end |