Just somewhere to keep my notes while I'm playing.

Showing posts with label object. Show all posts
Showing posts with label object. Show all posts

Tuesday, July 12, 2016

Learning Ruby - First Object

Learning how to construct an object in Ruby, this is what I have so far.

class Coin
  attr_reader :face, :value
  @@FaceRange = [0, 1]
  @@ValidValues = [1, 2, 5, 10, 20, 50, 100, 200]
  @@prng = Random.new # Pseudo-random Number Generator
  # Default Face to an illegal value so that it will flip the coin
  def initialize (value=10, face=-1) # CONSTRUCTOR
    self.value = value
    self.face = face
  end
  def face= (new_face)        # Set a valid face
    @face ||= 0 # default
    if @@FaceRange.include? new_face
      @face = new_face
    else
      self.flip
    end
  end
  def value= (new_value)      # Set a valid value
    @value ||= 1 # default
    @value = new_value if @@ValidValues.include? new_value
  end
  def set_face (new_face)     # Set face to a chosen value
     @face = new_face if [0, 1].include? new_face
  end
  def turn                    # Turn the coin over
     @face = (@face + 1).modulo(2)
  end
  def flip                    # Flip the coin
    @face = @@prng.rand(0..1)
  end
  def to_s # Over-ride the to_s method inherited from the Object class
    "Value is #{@value} Face is #{@face}"
  end
end

coin1 = Coin.new(20, 1)
puts coin1.face, coin1.value
puts coin1
coin1.set_face(0)
puts coin1

coin2 = Coin.new(50, 0)
puts "Coin 2 is #{coin2}"
coin2.set_face(0)
puts "Coin 2 is #{coin2}"
puts "Turn it"
coin2.turn
puts "Coin 2 is #{coin2}"
puts "Turn it"
coin2.turn
puts "Coin 2 is #{coin2}"

puts "Flip it"
coin2.flip
puts "Coin 2 is #{coin2}"
puts "Flip it"
coin2.flip
puts "Coin 2 is #{coin2}"
puts "Flip it"
coin2.flip
puts "Coin 2 is #{coin2}"
puts "Turn it"
coin2.turn
puts "Coin 2 is #{coin2}"

coin3 = Coin.new(5)
puts "Coin 3 is #{coin3}"

coin4 = Coin.new
puts "Coin 4 is #{coin4}"
puts "Flip it"
coin4.flip
puts "Coin 4 is #{coin4}"


$ ruby  coins2.rb
1
20
Value is 20 Face is 1
Value is 20 Face is 0
Coin 2 is Value is 50 Face is 0
Coin 2 is Value is 50 Face is 0
Turn it
Coin 2 is Value is 50 Face is 1
Turn it
Coin 2 is Value is 50 Face is 0
Flip it
Coin 2 is Value is 50 Face is 1
Flip it
Coin 2 is Value is 50 Face is 1
Flip it
Coin 2 is Value is 50 Face is 1
Turn it
Coin 2 is Value is 50 Face is 0
Coin 3 is Value is 5 Face is 1
Coin 4 is Value is 10 Face is 1
Flip it
Coin 4 is Value is 10 Face is 0

tjinkers@TJINKERS-LAP ~/ruby
$