Skip to content

Instantly share code, notes, and snippets.

@mmhan
Last active April 27, 2016 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmhan/ebb2aaf19682ffc49e23c00b957de634 to your computer and use it in GitHub Desktop.
Save mmhan/ebb2aaf19682ffc49e23c00b957de634 to your computer and use it in GitHub Desktop.
class Person
@@klass_name = "Person"
def initialize(name)
@name = name
end
def self.klass_name
@@klass_name
end
attr_reader :name
attr_writer :name
def say_hi
@@klass_name = "Person stuff"
puts "#{@@klass_name}:#{name} says hi"
end
def klass_name
@@klass_name
end
end
→ irb -r ./person.rb
2.1.6 :001 > a = Person.new "A"
=> #<Person:0x007fc3aa507c68 @name="A">
2.1.6 :002 > b = Person.new "B"
=> #<Person:0x007fc3aa4f68a0 @name="B">
2.1.6 :003 > a.name
=> "A"
2.1.6 :004 > b.name
=> "B"
2.1.6 :005 > a.say_hi
Person stuff:A says hi
=> nil
2.1.6 :006 > b.klass_name
=> "Person stuff"
2.1.6 :007 > exit
# 3 aspects of a test
# To test whether the code you write performs what you wants it to do.
#
# - Pre-condition
# - Action
# - Asserting that the result is what you expected.
## Add
# Pre-condition
# def add(a, b)
#
# - Need 2 params
# - Prepare param
param_a = 1
param_b = 2
# Action
# run the code that you wrote
# - Assert
raise if result != 3
# With rspec Action + Assertion
expect(add(a, b)).to eq(3)
## def dice
## rand(6) + 1
## end
## class SnakeGame
## @position = 1
##
## def play
## @position += dice
## end
##
## def positon
## @position
## end
## end
# Precondition
game = SnakeGame.new
expect(Dice).to receive(:dice).and_return 2 #assertion/pre-condition
# Action
game.play
result = game.position
# Assert
expect(result).to eq(3)
class Universe
attr_accessor :stuffs
def initialize
@stuffs = []
# @ this
# @@ this.class
end
def self.get(type)
if type == "a"
@a_single_universe ||= Universe.new
elsif type == "b"
@b_single_universe ||= Universe.new
end
# @@single_universe = Universe.new unless @@single_universe
end
def put(a)
stuffs << a
end
end
→ irb -r ./universe.rb
2.1.6 :001 > a = Universe.get "a"
=> #<Universe:0x007fce03612c08 @stuffs=[]>
2.1.6 :002 > a.put 1
=> [1]
2.1.6 :003 > a.put 2
=> [1, 2]
2.1.6 :004 > a.put 3
=> [1, 2, 3]
2.1.6 :005 > a
=> #<Universe:0x007fce03612c08 @stuffs=[1, 2, 3]>
2.1.6 :006 > b = Universe.get "b"
=> #<Universe:0x007fce035d9fe8 @stuffs=[]>
2.1.6 :007 > b.put 1
=> [1]
2.1.6 :008 > b.put 2
=> [1, 2]
2.1.6 :009 > a
=> #<Universe:0x007fce03612c08 @stuffs=[1, 2, 3]>
2.1.6 :010 > b
=> #<Universe:0x007fce035d9fe8 @stuffs=[1, 2]>
2.1.6 :011 > Universe.get "a"
=> #<Universe:0x007fce03612c08 @stuffs=[1, 2, 3]>
2.1.6 :012 > exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment