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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With