Strange ruby multiplication error

undefined method "*" for nil:NilClass (NoMethodError)

Page 1 of 1

2 Replies - 3561 Views - Last Post: 03 May 2009 - 03:11 PM Rate Topic: -----

#1 timothybrown   User is offline

  • New D.I.C Head
  • member icon

Reputation: -1
  • View blog
  • Posts: 46
  • Joined: 08-April 09

Strange ruby multiplication error

Posted 02 May 2009 - 03:26 PM

Basically, I'm getting a NoMethodError for the multiplication operator (*) on line 8.

This is a friend of mine's program, I didn't design it.

# Coefficent is designed to be an array
class Stuff
  def evaluate(coefficent, x)
	b = 0
	degree = (coefficent.length) - 1
	value = 0
	while b != (coefficent.length + 1)
	  value += (coefficent[b] * x**degree)
	  b = b + 1
	  degree = degree - 1
	end
	return value
  end
end

#-----
$stuff = Stuff.new
#-----

class Program
  def main
	a = [1,2,3]
	p $stuff.evaluate(a,17)
  end
end

#-----
$pub_main = Program.new
#-----
$pub_main.main
#-----



Is This A Good Question/Topic? 0
  • +

Replies To: Strange ruby multiplication error

#2 vikhyat   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 10
  • Joined: 15-February 09

Re: Strange ruby multiplication error

Posted 03 May 2009 - 12:03 AM

On line 8, coeffecient[b] is probably a nil. Try putting- "p coeffecient[b]" just before the line that is causing the problem.
Was This Post Helpful? 0
  • +
  • -

#3 JackOfAllTrades   User is offline

  • Saucy!
  • member icon

Reputation: 6259
  • View blog
  • Posts: 24,028
  • Joined: 23-August 08

Re: Strange ruby multiplication error

Posted 03 May 2009 - 03:11 PM

Are you sure you want
while b != (coefficent.length + 1)
???

A more Ruby way:
class Stuff
  def evaluate(coefficient, x)
    degree = coefficient.length - 1
    value = 0
    coefficient.each { |c| 
      value += (c * x**degree) 
      degree = degree - 1 
    }
    return value
  end
end

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1