jeffrey
jeffrey

Reputation: 2096

How to call a method in Ruby?

Hey I have a problem with my method that calculates the covariance of two arrays.

There is always the error:

undefined method 'kovarianz' for main:Object

Here is my Code:

rohstoff1 = "Eisen"
rohstoff2 = "Neodym"

daten_rohstoff1 = [1,2,3,4,5,6]
daten_rohstoff2 = [10,11,15,16,17,18]

module Enumerable
  def mean
    m = self.reduce(:+) / self.length.to_f
    return m
  end

  def covariance (dat1,dat2)
    kovar = dat1.inject(0) { |sum, x| sum + (x-dat1.mean) } *
    dat2.inject(0) { |sum, x, i| sum + (x-dat2.mean) } / dat1.length.to_f
    return kovar
  end
end

puts "Kovarianz von #{rohstoff1} und #{rohstoff2} = " +
covariance(daten_rohstoff1,daten_rohstoff2)

Upvotes: 0

Views: 786

Answers (3)

davidcelis
davidcelis

Reputation: 3347

There are two things wrong with what you're doing. First, you've defined an Enumerable instance method, not a class method. You won't pass in the array you are operating on but, rather, you will call covariance directly on the array:

daten_rohstoff1.covariance daten_rohstoff2

You should therefore define the method to take only one argument, namely the second array.

Second, and as mentioned before, you've defined a method covariance but are trying to call kovarianz. This, obviously, will not work.

Upvotes: 3

Mark
Mark

Reputation: 684

Well, the primary issue here being that you called kovarianz, as opposed to covariance, but the fact that the code is also embedded in a module means you have to call it like so:

Enumerable::covariance(daten_rohstoff1,daten_rohstoff2)

Hope this helped.

Upvotes: 1

Michelle Tilley
Michelle Tilley

Reputation: 159095

The method name is called covariance but you call kovarianz in the last line. Change one or the other and you should be golden.

Upvotes: 1

Related Questions