Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoMethodError when there is a method

Tags:

ruby

I am creating a Die class that has a function to output the number of the die. It has been named both printout and output, but the function continues to fail because of a NoMethodError. This is my code:

class Die

  def initialize()
    @number = rand(7)
  end

  def output()
    puts @number
  end

  def roll()
    @number = rand(7)
  end

end

Die.new.roll.output

Here is my error when I run the code:

undefined method `output' for 2:Integer (NoMethodError)

Any ideas?

like image 529
Jraokmepala Avatar asked Aug 20 '26 20:08

Jraokmepala


1 Answers

You must call like this:

die = Die.new
die.output # => 1
die.roll
die.output # => 3

First you need to instantiate the object (Die.new) into a variable (die). Then call your method on it.

Note: better to use rand(1..6)

Without using a variable, the better you can do is:

Die.new.output # => 3

It is not possible chain methods as you did (or follow the answer by Martin Zinovsky)

like image 181
iGian Avatar answered Aug 22 '26 13:08

iGian