0

I'm trying to write a coin flip program where I can analyze the percentage of Heads flipped. I've gotten coin flip to work, just not the actually analyzing yet.

The problem is when I created a Coin class in order to further break down the object into something like Coin.length afterwards.

Why am I getting an "undefined method 'flip' for Coin:Class (NoMethodError)" from flip.rb:14:in 'times' from flip.rb:14:in <main> when I indeed have one?

class Coin

def flip
  flip = 1 + rand(2)
    if flip == 2 
        then puts "Heads"
    else
        puts "Tails"
    end
end 

end

10.times do
  Coin.flip
end

Here's a die roll example that I am somewhat trying to emulate:

 class Die

     def roll
       1 + rand(6)
     end

  end

    #  Let's make a couple of dice...
    dice = [Die.new, Die.new]

    #  ...and roll them.
    dice.each do |die|
      puts die.roll
    end
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Tony
  • 981
  • 5
  • 16
  • 30

2 Answers2

3

Coin.flip is not a method you defined; this would be a class method, and to define a class method called flip you would write:

class Coin
  def self.flip
    ...
  end
end

What you created is an instance method, and as such it requires that it is called on an instance:

coin = Coin.new
coin.flip
# or
Coin.new.flip

In your second example (with the Dice), you are correctly calling new and creating instances.

Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
2

you defined instance method filp, but there is no class method called Coin.flip.

Jokester
  • 5,501
  • 3
  • 31
  • 39