Jerome Jerome - 2 months ago 9
Ruby Question

Undefined method in ruby

I'm a beginner in Ruby and I'm doing a really easy "game".

My problem is that I want to test if the user press

1
then roll some dices but I can't use my method. Please refer to the code below for more details:

class Player
#i have some methods but it work
end

class Game
tot = 0
def rollDice
tot = 0
puts "You roll the dices"
d1 = rand(1..6)
puts "Dice 1: #{d1}"
d2 = rand(1..6)
puts "Dice 2: #{d2}"
d3 = rand(1..6)
puts "Dice #{d3}"
tot = d1 + d2 + d3
puts "Your score is #{tot}"
return tot
end

#some puts but not important for the coding

puts "Press 1 to play or 2 to leave"
value = gets.chomp
if value == "1"
s1 = rollDice
puts "Why it doesnt work :C #{s1}"

#[i have a player class but its not important for the moment]
#player1 = Joueur.new(j1)
#player2 = Joueur.new(j2)

#player1.score
#player2.score
elsif value== "2"
exit
end
end


But i have the undefined method error for my method rollDice
thank you really

Answer

Your code does work. However, your rollDice definition is indented (and you have a second tot=0 call), so I guess you actually defined it in something else (a class?), which is at the time of writing not included in your posted code sample.

Btw, following conventions/style guides I would suggest you to rename rollDice into roll_dice.

The code I tested successfully is this one:

def rollDice
    tot = 0
    puts "You roll the dices"
    d1 = rand(1..6)
    puts "Dice 1: #{d1}"
    d2 = rand(1..6)
    puts "Dice 2: #{d2}"
    d3 = rand(1..6)
    puts "Dice #{d3}"
    tot = d1 + d2 + d3
    puts "Your score is  #{tot}"
    return tot
end☠

puts "Press 1 to play or 2 to leave"
value = gets.chomp
if value == "1"
    s1 = rollDice
    puts "Why it doesnt work :C #{s1}"

elsif value== "2"
    exit
end

example session:

$ Press 1 to play or 2 to leave
> 1
You roll the dices
Dice 1: 5
Dice 2: 5
Dice 2
Your score is  12
Why it doesnt work :C 12