Skip to content

Instantly share code, notes, and snippets.

@mhriess
Forked from dbc-challenges/card.rb
Created October 18, 2012 19:11
Show Gist options
  • Save mhriess/3914160 to your computer and use it in GitHub Desktop.
Save mhriess/3914160 to your computer and use it in GitHub Desktop.
FlashCardinator
require 'csv'
require 'term/ansicolor'
# Use this trick to work around namespace cluttering that
# happens if you just include Term::ANSIColor:
class Color
extend Term::ANSIColor
end
class FlashCardinator
attr_reader :deck_position, :current_card, :deck, :wrong_guess_counter
def initialize(deck)
@deck = deck
@deck_position = random_deck_position
@current_card = set_current_card
@user_input = ''
@wrong_guess_counter = 0
end
def start
loop do
next_card
card_definition
get_input
correct? ? correct_guess_message : wrong_guess
exit if @user_input == "exit"
end
end
def get_input
@user_input = gets.chomp
end
def correct?
@user_input == @current_card.term
end
def correct_guess_message
puts "Right!"
end
def wrong_guess
increment_wrong_guess
until (max_guesses? || correct?)
wrong_guess_message
get_input
increment_wrong_guess
end
correct? ? correct_guess_message : display_answer
end
def wrong_guess_message
puts "#{Color.red}Wrong! Try again!#{Color.clear}"
end
def increment_wrong_guess
@wrong_guess_counter += 1
end
def display_answer
puts "#{Color.yellow}The correct answer was '#{@current_card.term}'#{Color.clear}."
end
def max_guesses?
@wrong_guess_counter == 3
end
def set_current_card
@current_card = @deck[@deck_position]
end
def random_deck_position
@deck_position = rand(@deck.length)
end
def card_definition
print "#{Color.bold}#{@current_card.definition} #{Color.clear}\n"
end
def next_card
@current_card = @deck[random_deck_position]
end
end
class Deck < Array
def initialize(file_name)
import(file_name)
end
def add(row)
self << Card.new(row)
end
private
def import(file_name)
File.open(file_name).each_line { |row| add(row) }
end
end
class Card
attr_reader :term, :definition
def initialize(card_data)
card_data.match(/(\w+)\s(.+)/)
@term, @definition = $1, $2
end
end
# FlashCardinator.new(Deck.new('flashcards_data.txt')).start
require 'SimpleCov'
SimpleCov.start
require './card.rb'
describe FlashCardinator do
before(:each) do
@flashcardinator = FlashCardinator.new(Deck.new('fake_flashcards_data.txt'))
end
subject { @flashcardinator }
context "when initializing a FlashCardinator" do
it "should exist" do
subject.should be
end
it "should set a current card" do
subject.current_card != nil
end
it "initializes a value for deck position" do
subject.deck_position.should be_kind_of(Integer)
end
end
context "when playing FlashCardinator" do
it "should take user input" do
subject.stub!(:gets) { "input" }
subject.get_input.should == "input"
end
it "chooses a card" do
subject.next_card.should be_kind_of(Card)
end
it "checks for a wrong answer" do
subject.correct?.should be_false
end
it "prints the answer" do
subject.display_answer
end
it "lets the user know when they get the answer right" do
subject.correct_guess_message
end
context "with a right answer" do
before { subject.stub!(:correct?) { true } }
before { subject.stub!(:user_input) { subject.current_card.term } }
it "should be true" do
subject.correct?.should be_true
end
it "should match the current card" do
subject.user_input.should eq(subject.current_card.term)
end
end
context "with a wrong answer" do
before { subject.stub!(:correct?) { false } }
it "should be false" do
subject.correct?.should be_false
end
it "should increment the number of wrong guesses by one" do
subject.stub_chain(:loop, :next_card, :get_input).and_return(:wrong_guess)
subject.stub!(:correct?) { true }
expect { subject.wrong_guess }.to change(subject, :wrong_guess_counter).by(1)
subject.wrong_guess_counter.should == 1
end
it "should only allow 3 wrong answers" do
3.times { subject.increment_wrong_guess }
subject.max_guesses?.should be_true
end
it "should display the definition again if a user hasn't guessed 3 times" do
2.times { subject.increment_wrong_guess }
subject.max_guesses?.should be_false
end
it "#wrong_guess_message prints wrong!" do
subject.wrong_guess_message
end
end
end
describe Deck do
it "imports data from a text file" do
subject.deck.should have_at_least(1).item
end
it "creates new cards" do
subject.deck[0].should be_kind_of(Card)
end
end
end
describe Card do
context "when creating cards" do
let(:card) { Card.new("alias To create a second name for the variable or method.")}
it "should have a term" do
card.term.should eq("alias")
end
it "should have a definition" do
card.definition.should eq("To create a second name for the variable or method.")
end
end
end
alias To create a second name for the variable or method.
and A command that appends two or more objects together.
BEGIN Designates code that must be run unconditionally at the beginning of the program before any other.
begin Delimits a "begin" block of code, which can allow the use of while and until in modifier position with multi-line statements.
break Gives an unconditional termination to a code block, and is usually placed with an argument.
case starts a case statement; this block of code will output a result and end when it's terms are fulfilled, which are defined with when or else.
class Opens a class definition block, which can later be reopened and added to with variables and even functions.
def Used to define a function.
defined? A boolean logic function that asks whether or not a targeted expression refers to anything recognizable in Ruby; i.e. literal object, local variable that has been initialized, method name visible from the current scope, etc.
do Paired with end, this can delimit a code block, much like curly braces; however, curly braces retain higher precedence.
else Gives an "otherwise" within a function, if-statement, or for-loop, i.e. if cats = cute, puts "Yay!" else puts "Oh, a cat."
elsif Much like else, but has a higher precedence, and is usually paired with terms.
END Designates, via code block, code to be executed just prior to program termination.
end Marks the end of a while, until, begin, if, def, class, or other keyword-based, block-based construct.
ensure Marks the final, optional clause of a begin/end block, generally in cases where the block also contains a rescue clause. The code in this term's clause is guaranteed to be executed, whether control flows to a rescue block or not.
false denotes a special object, the sole instance of FalseClass. false and nil are the only objects that evaluate to Boolean falsehood in Ruby (informally, that cause an if condition to fail.)
for A loop constructor; used in for-loops.
if Ruby's basic conditional statement constructor.
in Used with for, helps define a for-loop.
module Opens a library, or module, within a Ruby Stream.
next Bumps an iterator, or a while or until block, to the next iteration, unconditionally and without executing whatever may remain of the block.
nil A special "non-object"; it is, in fact, an object (the sole instance of NilClass), but connotes absence and indeterminacy. nil and false are the only two objects in Ruby that have Boolean falsehood (informally, that cause an if condition to fail).
not Boolean negation. i.e. not true # false, not 10 # false, not false # true.
or Boolean or. Differs from || in that or has lower precedence.
redo Causes unconditional re-execution of a code block, with the same parameter bindings as the current execution.
rescue Designates an exception-handling clause that can occur either inside a begin<code>/<code>end block, inside a method definition (which implies begin), or in modifier position (at the end of a statement).
retry Inside a rescue clause, causes Ruby to return to the top of the enclosing code (the begin keyword, or top of method or block) and try executing the code again.
return Inside a method definition, executes the ensure clause, if present, and then returns control to the context of the method call. Takes an optional argument (defaulting to nil), which serves as the return value of the method. Multiple values in argument position will be returned in an array.
self The "current object" and the default receiver of messages (method calls) for which no explicit receiver is specified. Which object plays the role of self depends on the context.
super Called from a method, searches along the method lookup path (the classes and modules available to the current object) for the next method of the same name as the one being executed. Such method, if present, may be defined in the superclass of the object's class, but may also be defined in the superclass's superclass or any class on the upward path, as well as any module mixed in to any of those classes.
then Optional component of conditional statements (if, unless, when). Never mandatory, but allows for one-line conditionals without semi-colons.
true The sole instance of the special class TrueClass. true encapsulates Boolean truth; however, <emph>all</emph> objects in Ruby are true in the Boolean sense (informally, they cause an if test to succeed), with the exceptions of false and nil.
undef Undefines a given method, for the class or module in which it's called. If the method is defined higher up in the lookup path (such as by a superclass), it can still be called by instances classes higher up.
unless The negative equivalent of if. i.e. unless y.score > 10 puts "Sorry; you needed 10 points to win." end.
until The inverse of while: executes code until a given condition is true, i.e., while it is not true. The semantics are the same as those of while.
when Same as case.
while Takes a condition argument, and executes the code that follows (up to a matching end delimiter) while the condition is true.
yield Called from inside a method body, yields control to the code block (if any) supplied as part of the method call. If no code block has been supplied, calling yield raises an exception.
# Your code here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment