Class: Tonal::Hertz

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/tonal/hertz.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(arg) ⇒ Tonal::Hertz

Examples:

Tonal::Hertz.new(1000.0) => 1000.0 Hz

Parameters:

Raises:

  • (ArgumentError)


11
12
13
14
# File 'lib/tonal/hertz.rb', line 11

def initialize(arg)
  raise ArgumentError, "Argument is not Numeric or Tonal::Hertz" unless arg.kind_of?(Numeric) || arg.kind_of?(self.class)
  @value = arg.kind_of?(self.class) ? arg.inspect : arg
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(op, *args, &blk) ⇒ Object



61
62
63
64
65
66
67
68
# File 'lib/tonal/hertz.rb', line 61

def method_missing(op, *args, &blk)
  rhs = args.collect do |arg|
    arg.kind_of?(self.class) ? arg.value : arg
  end
  result = value.send(op, *rhs)
  return result if op == :coerce
  result.kind_of?(Numeric) ? self.class.new(result) : result
end

Instance Attribute Details

#valueObject (readonly)

Returns the value of attribute value.



4
5
6
# File 'lib/tonal/hertz.rb', line 4

def value
  @value
end

Class Method Details

.referenceTonal::Hertz

Returns 440 Hz.

Examples:

Tonal::Hertz.reference => 440.0 Hz

Returns:



20
21
22
# File 'lib/tonal/hertz.rb', line 20

def self.reference
  self.new(440.0)
end

Instance Method Details

#<=>(rhs) ⇒ Object



57
58
59
# File 'lib/tonal/hertz.rb', line 57

def <=>(rhs)
  rhs.kind_of?(self.class) ? value <=> rhs.value : value <=> rhs
end

#inspectString

Returns the string representation of Tonal::Hertz.

Examples:

Tonal::Hertz(1000.0).inspect => "1000.0 Hz"

Returns:

  • (String)

    the string representation of Tonal::Hertz



53
54
55
# File 'lib/tonal/hertz.rb', line 53

def inspect
  "#{value} Hz"
end

#to_cents(reference: self.class.reference) ⇒ Tonal::Cents

Returns the cents difference between self and a reference frequency.

Examples:

Tonal::Hertz.new(880).to_cents => 1200.0

Parameters:

  • reference (Tonal::Hertz, Numeric) (defaults to: self.class.reference)

    the reference frequency to compare to

Returns:

  • (Tonal::Cents)

    the cents difference between self and a reference frequency



45
46
47
# File 'lib/tonal/hertz.rb', line 45

def to_cents(reference: self.class.reference)
  Tonal::Cents.new(ratio: to_r / reference.to_r)
end

#to_fRational

Returns self as a float.

Examples:

Tonal::Hertz.new(440).to_f => 440.0

Returns:

  • (Rational)

    self as a float



36
37
38
# File 'lib/tonal/hertz.rb', line 36

def to_f
  value.to_f
end

#to_rRational

Returns self as a rational.

Examples:

Tonal::Hertz.new(440).to_r => (440/1)

Returns:

  • (Rational)

    self as a rational



28
29
30
# File 'lib/tonal/hertz.rb', line 28

def to_r
  Rational(value)
end