diff --git a/final/features/step_definitions/tic-tac-toe-steps.rb b/final/features/step_definitions/tic-tac-toe-steps.rb new file mode 100644 index 0000000..aa42bed --- /dev/null +++ b/final/features/step_definitions/tic-tac-toe-steps.rb @@ -0,0 +1,149 @@ +require 'rspec/mocks/standalone' +require 'rspec/expectations' + + +Given /^I start a new Tic\-Tac\-Toe game$/ do + @game = TicTacToe.new +end + +When /^I enter my name (\w+)$/ do |name| + @game.player = name +end + +Then /^the computer welcomes me to the game with "(.*?)"$/ do |arg1| + #@game.welcome_player.should eq arg1 + expect(@game.welcome_player).to eq arg1 +end + +Then /^randomly chooses who goes first$/ do + #[@game.player, "Computer"].should include @game.current_player + expect([@game.player, "Computer"]).to include(@game.current_player) +end + +Then /^who is X and who is O$/ do + #TicTacToe::SYMBOLS.should include @game.player_symbol, @game.computer_symbol + expect(TicTacToe::SYMBOLS).to include(@game.player_symbol, @game.computer_symbol) +end + +Given /^I have a started Tic\-Tac\-Toe game$/ do + @game = TicTacToe.new(:player) + @game.player = "Renee" +end + +Given /^it is my turn$/ do + #@game.current_player.should eq "Renee" + expect(@game.current_player).to eq "Renee" +end + +Given /^the computer knows my name is Renee$/ do + #@game.player.should eq "Renee" + expect(@game.player).to eq "Renee" +end + +Then /^the computer prints "(.*?)"$/ do |arg1| + #@game.should_receive(:puts).with(arg1) + expect(@game).to receive(:puts).with(arg1) + @game.indicate_player_turn +end + +Then /^waits for my input of "(.*?)"$/ do |arg1| + #@game.should_receive(:gets).and_return(arg1) + expect(@game).to receive(:gets).with(arg1) + #@game.get_player_move +end + +Given /^it is the computer's turn$/ do #' + @game = TicTacToe.new(:computer, :X) + #@game.current_player.should eq "Computer" + expect(@game.current_player).to eq "Computer" +end + +Then /^the computer randomly chooses an open position for its move$/ do + open_spots = @game.open_spots + @com_move = @game.computer_move + #open_spots.should include(@com_move) + expect(open_spots).to include(@com_move) +end + +Given /^the computer is playing X$/ do + #@game.computer_symbol.should eq :X + expect(@game.computer_symbol).to eq :X +end + +Then /^the board should have an X on it$/ do + #@game.current_state.should include 'X' + expect(@game.current_state).to include 'X' + +end + +Given /^I am playing X$/ do + @game = TicTacToe.new(:player, :X) + #@game.player_symbol.should eq :X + expect(@game.player_symbol).to eq :X +end + +When /^I enter a position "(.*?)" on the board$/ do |arg1| + @old_pos = @game.board[arg1.to_sym] + #@game.should_receive(:get_player_move).and_return(arg1) + expect(@game).to receive(:get_player_move).and_return(arg1) + #@game.player_move.should eq arg1.to_sym + expect(@game.player_move).to eq arg1.to_sym +end + +When /^"(.*?)" is not taken$/ do |arg1| + #@old_pos.should eq " " + expect(@old_pos).to eq "" +end + +Then /^it is now the computer's turn$/ do #' + #@game.current_player.should eq "Computer" + expect(@game.current_player).to eq "Computer" +end + +When /^there are three X's in a row$/ do #' + @game = TicTacToe.new(:player, :X) + @game.board[:C1] = @game.board[:B2] = @game.board[:A3] = :X +end + +Then /^I am declared the winner$/ do + @game.determine_winner + #@game.player_won?.should be_true + expect(@game.player_won?).to be true +end + +Then /^the game ends$/ do + #@game.over?.should be_true + expect(@game.over?).to be true +end + +Given /^there are not three symbols in a row$/ do + @game.board = { + :A1 => :X, :A2 => :O, :A3 => :X, + :B1 => :X, :B2 => :O, :B3 => :X, + :C1 => :O, :C2 => :X, :C3 => :O + } + @game.determine_winner +end + +When /^there are no open spaces left on the board$/ do + #@game.spots_open?.should be_false + expect(@game.spots_open?).to be false +end + +Then /^the game is declared a draw$/ do + #@game.draw?.should be_true + expect(@game.draw?).to be true +end + +When /^"(.*?)" is taken$/ do |arg1| + @game.board[arg1.to_sym] = :O + @taken_spot = arg1.to_sym +end + +Then /^computer should ask me for another position "(.*?)"$/ do |arg1| + @game.board[arg1.to_sym] = '' + #@game.should_receive(:get_player_move).twice.and_return(@taken_spot, arg1) + expect(@game).to receive(:get_player_move).twice.and_return(@taken_spot, arg1) + #@game.player_move.should eq arg1.to_sym + expect(@game.player_move).to eq arg1.to_sym +end diff --git a/final/features/step_definitions/tic_tac_toe.rb b/final/features/step_definitions/tic_tac_toe.rb new file mode 100644 index 0000000..1dcac58 --- /dev/null +++ b/final/features/step_definitions/tic_tac_toe.rb @@ -0,0 +1,122 @@ +#UW Ruby class Fall 2014 joseph Simpson +class TicTacToe + PLAYERS = [:player, :computer] + SYMBOLS = [:X, :O] + attr_accessor :player, :board + + def initialize(initial_player = nil, initial_symbol=nil) + @current_player = initial_player || PLAYERS.sample + @player_symbol = initial_symbol || SYMBOLS.sample + + @board = { + :A1 => '', :A2 => '', :A3 => '', + :B1 => '', :B2 => '', :B3 => '', + :C1 => '', :C2 => '', :C3 => '' + } + end + + def welcome_player + "Welcome #{@player}" + end + + def current_player + {:player => @player, :computer => 'Computer' } [@current_player] + end + + def player_symbol + @player_symbol + end +3 + def computer_symbol + if current_player == 'Computer' + computer_symbol = {:X => :X, :O => :O}[@player_symbol] + else + computer_symbol = {:X => :O, :O => :X}[@player_symbol] + end + end + + def indicate_player_turn + puts "#{current_player}'s Move:" + end + + def open_spots + @empty_spots = [] + @board.each { |index, vaue| @empty_spots << index if @board[index].empty? } + @empty_spots + end + + def computer_move + move_spot = open_spots.sample + @board[move_spot] = { :X => 'X', :O => 'O' }[computer_symbol] + @current_player = :player + move_spot + end + + def current_state + state = "#{@board[:A1]} | #{@board[:A2]} | #{@board[:A3]} \n \ + #{@board[:B1]} | #{@board[:B2]} | #{@board[:B3]} \n \ + #{@board[:C1]} | #{@board[:C2]} | #{@board[:C3]} \n " + end + + def get_player_move + gets.chomp + end + + def player_move + guard_num = 0 + player_spot = get_player_move.to_sym + until open_spots.include?(player_spot) || guard_num > 10 + guard_num = guard_num + 1 + player_spot = get_player_move.to_sym + end + @board[player_spot] = player_symbol + @current_player = :computer + player_spot + end + + def determine_winner + @player_win = false + @computer_win = false + @draw_match = false + if score_win(player_symbol) + return @player_win = true + else if score_win(computer_symbol) + return @computer_win = true + else + return @draw_match = true + end + end + + end + + def score_win(symbol) + return true if + @board[:A1] == symbol && @board[:A2] == symbol && @board[:A3] == symbol || #row 1 + @board[:B1] == symbol && @board[:B2] == symbol && @board[:B3] == symbol || #row 2 + @board[:C1] == symbol && @board[:C2] == symbol && @board[:C3] == symbol || #row 3 + @board[:A1] == symbol && @board[:B1] == symbol && @board[:C1] == symbol || #column 1 + @board[:A2] == symbol && @board[:B2] == symbol && @board[:C2] == symbol || #column 2 + @board[:A3] == symbol && @board[:B3] == symbol && @board[:C3] == symbol || #column 3 + @board[:A2] == symbol && @board[:B2] == symbol && @board[:C2] == symbol || #diagonal 1 + @board[:A3] == symbol && @board[:B3] == symbol && @board[:C3] == symbol #diagonal 2 + + else return false + end + + def player_won? + !@player_win + end + + def over? + player_won? || @computer_win || open_spots.length == 0 + end + + def spots_open? + !open_spots.empty? + end + + def draw? + !@computer_win && !@player_win + end + +end \ No newline at end of file diff --git a/final/features/tic-tac-toe.feature b/final/features/tic-tac-toe.feature new file mode 100644 index 0000000..6f3134d --- /dev/null +++ b/final/features/tic-tac-toe.feature @@ -0,0 +1,57 @@ +Feature: Tic-Tac-Toe Game + As a game player I like tic-tac-toe + In order to up my skills + I would like to play agaist the computer + +Scenario: Begin Game + Given I start a new Tic-Tac-Toe game + When I enter my name Renee + Then the computer welcomes me to the game with "Welcome Renee" + And randomly chooses who goes first + And who is X and who is O + +Scenario: My Turn + Given I have a started Tic-Tac-Toe game + And it is my turn + And the computer knows my name is Renee + Then the computer prints "Renee's Move:" + And waits for my input of "B2" + +Scenario: Computer's Turn + Given I have a started Tic-Tac-Toe game + And it is the computer's turn + And the computer is playing X + Then the computer randomly chooses an open position for its move + And the board should have an X on it + +Scenario: Making Moves + Given I have a started Tic-Tac-Toe game + And it is my turn + And I am playing X + When I enter a position "A1" on the board + And "A1" is not taken + Then the board should have an X on it + And it is now the computer's turn + +Scenario: Making Bad Moves + Given I have a started Tic-Tac-Toe game + And it is my turn + And I am playing X + When I enter a position "A1" on the board + And "A1" is taken + Then computer should ask me for another position "B2" + And it is now the computer's turn + +Scenario: Winning the Game + Given I have a started Tic-Tac-Toe game + And I am playing X + When there are three X's in a row + Then I am declared the winner + And the game ends + +Scenario: Game is a draw + Given I have a started Tic-Tac-Toe game + And there are not three symbols in a row + When there are no open spaces left on the board + Then the game is declared a draw + And the game ends diff --git a/hello b/hello new file mode 100644 index 0000000..3ce9529 --- /dev/null +++ b/hello @@ -0,0 +1,6 @@ +hi +gobbly gook +hi from pry +hello +hi +last line \ No newline at end of file diff --git a/week1/exercises/rspec_spec.rb b/week1/exercises/rspec_spec.rb index c4c5e0b..88bdd7e 100644 --- a/week1/exercises/rspec_spec.rb +++ b/week1/exercises/rspec_spec.rb @@ -8,26 +8,26 @@ it "creates examples with the #it keyword" do # this test code passes, so this example passes - 1.should eq 1 + expect(1).to eq 1 end it "has keywords like #context, and #describe to help organize the spec, or specification" do # test code goes here - (1+2).should eq 3 + expect(1+2).to eq 3 end - it "has easily readable methods like #should to test any object" do + it "has easily readable methods like #should (should is deprcated use expect(x).to eq x) to test any object" do - "Hello".should eq "Hello" + expect("Hello").to eq "Hello" end - it "has #should_not to test for negative cases" do + it "has #should_not (should_not is deprecated use expect(x).not_to eq y) test for negative cases" do - 1.should_not eq 2 + expect(1).not_to eq 2 end @@ -35,8 +35,8 @@ # Integers have #zero? and #nil? predicate methods, so # rspec automatically supports the #be_zero and #be_nil parameter to #should_not method - 1.should_not be_zero - 1.should_not be_nil + expect(1).not_to be_zero + expect(1).not_to be_nil end @@ -44,7 +44,9 @@ # When this example fails, # it will show "expected" as 2, and "actual" as 1 - 1.should eq 2 + #expect(1).to eq 2 + expect(1).to eq 1 + end @@ -58,17 +60,18 @@ # The following line of code is correct, and would cause the example to fail: # true.should == false + # expect(true).to eq false # Lesson: It's easy to write bad tests. end it "should count the characters in my name" do - "Renée".should have(5).characters + expect("Renée").to have(5).characters end it "should check how to spell my name" do - "Renée".should include("ée") + expect("Renée").to include("ée") end end @@ -78,18 +81,18 @@ # Fix the Failing Test # Order of Operations is Please Excuse My Dear Aunt Sally: # Parentheses, Exponents, Multiplication, Division, Addition, Subtraction - (1+2-5*6/2).should eq -12 + expect(1+2-5*6/2).to eq -12 end it "should count the characters in your name" do - "Tom".should have(3).characters + expect("Tom").to have(3).characters end it "should check basic math" do - (1+1).should eq 2 + expect(1+1).to eq 2 end it "should check basic spelling" do - "field".should include("ie") + expect("field").to include("ie") end end diff --git a/week1/homework/questions.txt b/week1/homework/questions.txt index 2257bb9..cdb4116 100644 --- a/week1/homework/questions.txt +++ b/week1/homework/questions.txt @@ -2,14 +2,51 @@ Please read: Chapter 3 Classes, Objects, and Variables p.86-90 Strings (Strings section in Chapter 6 Standard Types) +My answers: 1. What is an object? +An object is a software artifact that encapsulates the behavior and state of the entity being modeled in the software object. Using software object modeling techniques a number of software architectural benefits may be achieved including: + - Modularity + - Information Hiding + - Code Reuse + - Replaceable Components 2. What is a variable? +Variables are software "tags or names" that are used to manage and track software objects. EAch variable holds a reference to an object. 3. What is the difference between an object and a class? +A software class is a general description or format for a class of things. A software object is a specific instance of a class that contains individual values for the class attributes that represent a specific object. 4. What is a String? +In Ruby, strings are a sequence of 8-bit bytes. Strings can hold binary and printable content. 5. What are three messages that I can send to a string object? Hint: think methods +The Ruby string class is one of the largest built-in Ruby classes, containing over 75 methods. Three of these methods (or messages) are: + - try_convert("some string") + - "some_string".capitalize + - "some_string".empty? + - "some_string".include? + 6. What are two ways of defining a String literal? Bonus: What is the difference between them? +A Ruby string literal may be defined using double quotes ("a string") or single quotes ('a string'). The double quotes string allow escaped characters and interpolated sections. Single quote strings do not allow interpolation. + + +Instructor answers: +An object is a representation in memory of a specific concept or thing that the Ruby interpreter knows about. + +2. What is a variable? +A variable is a name for a location in memory. It can contain, or point to, any type of object. + +3. What is the difference between an object and a class? +An object is an instance of a class, or a specific thing of that class's type in memory. The class is the specifics that are common to all things of that type. The classification of a concept or a thing is a class. A specific thing or concept of a class's type in memory is an object. For example: All books have titles (Class). This book's title is "Harry Potter and the Goblet of Fire" (Object). + +4. What is a String? +A string is how Ruby understands text. It is a collection of characters (Bytes), and can be created by making an instance of the String class (String.new) or as a string literal ("",'', %Q[]). + +5. What are three messages that I can send to a string object? Hint: think methods +chomp! - removes newline characters, or the specified characters, from the end of a string +strip! - removes leading or trailing whitespace from a string +split - returns an array of strings made up of the original string separated on whitespace or the specified characters or regexp + +6. What are two ways of defining a String literal? Bonus: What is the difference between the two? +Single quotes ex: '' and Double quotes ex: "". The single quotes allow for 2 escape characters: \' and \\ . The double quoted string literal allows for many different escaped special characters (like \n is a line break) and allows for string interpolation, or the injection of evaluated Ruby code into the string ex: "Hello #{my_name}". The single quoted string takes up much less memory than a double quoted string with interpolation. Without interpolation, both are about the same. diff --git a/week1/homework/strings_and_rspec_spec.rb b/week1/homework/strings_and_rspec_spec.rb index 496e61d..6388b27 100644 --- a/week1/homework/strings_and_rspec_spec.rb +++ b/week1/homework/strings_and_rspec_spec.rb @@ -1,7 +1,8 @@ +# encoding: utf-8 + require 'rspec/collection_matchers' require_relative '../../spec_helper' -# encoding: utf-8 # Please make these examples all pass # You will need to change the 3 pending tests @@ -16,18 +17,19 @@ @my_string = "Renée is a fun teacher. Ruby is a really cool programming language" end - it "should be able to count the charaters" + it "should be able to count the characters" do + expect(@my_string.length).to eq 66 + end - it "should be able to split on the . charater" do - pending - result = #do something with @my_string here - result.should have(2).items + it "should be able to split on the . character" do + result = @my_string.split(/[.]/) + expect(result.length).to eq 2 end it "should be able to give the encoding of the string" do - pending 'helpful hint: should eq (Encoding.find("UTF-8"))' - encodeing #do something with @my_string here - #use helpful hint here + #pending 'helpful hint: should eq (Encoding.find("UTF-8"))' + encode = Encoding.find("UTF-8") + expect(@my_string.encoding).to eq encode end end end diff --git a/week2/examples/book.rb b/week2/examples/book.rb new file mode 100644 index 0000000..41b2a53 --- /dev/null +++ b/week2/examples/book.rb @@ -0,0 +1,27 @@ +class Book + + @@book_count = 0 + + def self.book_count + @@book_count + end + + attr_accessor :title, :pages, :author + + def initialize title = "unknown", author: "unknown", pages: 0 + @pages = pages + @author = author + @title = title + @@book_count += 1 + end + + def pages + @pages + end + + + def book_count + @@book_count + end + +end \ No newline at end of file diff --git a/week2/examples/book_spec.rb b/week2/examples/book_spec.rb new file mode 100644 index 0000000..7a28453 --- /dev/null +++ b/week2/examples/book_spec.rb @@ -0,0 +1,41 @@ +require_relative '../../spec_helper' +require_relative 'book' + +describe Book do + + before :each do + @my_book = Book.new + end + + it "should count the books in our library" do + Book.new + Book.book_count.should eq 2 + end + + it "should have a title" do + @my_book.should respond_to "title" + end + + it "should not have a nil title" do + @my_book.title.should_not be_nil + end + + it "should have a non empty title" do + @my_book.title.size.should > 0 + end + + it "should have a default title of unknown" do + @my_book.title.should eq 'unknown' + end + + it "should allow us to set the title on a new instance" do + book = Book.new "Programming Ruby" + book.title.should eq "Programming Ruby" + end + + it "should let me set a title" do + @my_book.title = "Harry Potter" + @my_book.title.should eq "Harry Potter" + end + +end diff --git a/week2/examples/mad_libs.rb b/week2/examples/mad_libs.rb new file mode 100644 index 0000000..9378eff --- /dev/null +++ b/week2/examples/mad_libs.rb @@ -0,0 +1,3 @@ +puts "enter a noun:" +noun = gets.chomp +puts "The #{noun} is cool." \ No newline at end of file diff --git a/week2/exercises/book.rb b/week2/exercises/book.rb index 34931fa..6dfa6ca 100644 --- a/week2/exercises/book.rb +++ b/week2/exercises/book.rb @@ -1,17 +1,32 @@ -class Book - attr_accessor :title - attr_reader :page_count - @@book_count = 0 +module ReneesLibrary + class Book + attr_accessor :title + def title + @title + end + def title=t + @title = t + end + attr_reader :page_count - def self.book_count - @@book_count - end + @@book_count = 0 + + def self.book_count + @@book_count + end + + def initialize title = "Not Set", page_count = 0 + @@book_count += 1 + @page_count = page_count + @title = title + end - def initialize title = "Not Set", page_count = 0 - @@book_count += 1 - @page_count = page_count - @title = title end +end +class Book + def self.book_count + 19 + end end \ No newline at end of file diff --git a/week2/homework/questions.txt b/week2/homework/questions.txt index 939e42d..fde79aa 100644 --- a/week2/homework/questions.txt +++ b/week2/homework/questions.txt @@ -1,13 +1,78 @@ +Homework Two (2) — Joseph Simpson UW Ruby Certificate Class - 10-16-2014 + Please Read The Chapters on: Containers, Blocks, and Iterators Sharing Functionality: Inheritance, Modules, and Mixins +My answers: 1. What is the difference between a Hash and an Array? +The difference between an Array and a Hash is the type of object used to +index the collection. An Array is indexed using an integer. A Hash is +indexed using any type of object. + +2. When would you use an Array over a Hash and vice versa? +An Array is naturally used for collections that have a clean linear +structure that intuitively maps to an increasing set of natural numbers +(whole integers). A Hash is used when the index object presents a more +complex index configuration or you need to map one object to another. + +3. What is a module? +From www.ruby-doc.org +"A module is a collection of methods and constants. The methods in a +module may be instance methods or module methods. Instance methods +appear as methods in a class when the module is included, module methods +do not. Conversely, module methods may be called without creating an +encapsulating object, while instance methods may not." + +A module is similar to a class but it can have no subclasses or instances. + +A module is defined by: +module ..... + . + . + . +end + + +Enumerable is a built in Ruby module, what is it? +From www.ruby-doc.org +"The Enumerable mixin provides collection classes with several traversal +and searching methods, and the ability to sort. The class must provide a +method each, which yields successive members of the collection. If +Enumerable#max, #min, or #sort is used, the objects in the collection +must also implement a meaningful <=> operator, as these methods rely on +an ordering between members of the collection." + +Ruby docs calls Enumerable a "mix-in" and not a module. So a module and +a mix-in must be the same thing. + +4. Can you inherit more than one thing in Ruby? +Ruby is designed for single inheritance, so a Ruby class can have only +one direct parent. + +How could you get around this problem? +The Ruby language supports mixins which are similar to classes in some +respects. A controlled type of multiple-inheritance-type behaviour may +achieved using Ruby mixins. + + +5. What is the difference between a Module and a Class? +A Ruby Class and a Ruby Module are very similar. However, a Ruby Module +should not support or encode object state information. If object state +information is needed then a Class should be written. + +Instructor answers: +An array is an ordered list of items that are referenced by their index (order), a hash is a collection of items that can be referenced by a key and have no order. 2. When would you use an Array over a Hash and vice versa? +When the items have an inherent order I would use an array, when I want to reference the items in my collection by a name or key and their order does not matter I would use a hash. 3. What is a module? Enumerable is a built in Ruby module, what is it? +A module is a way to group code that you can use across multiple classes. Enumerable is a Ruby module that provides collection functionality; iteration, searching, and sorting. It requires an implementation of the each method. 4. Can you inherit more than one thing in Ruby? How could you get around this problem? +No, multiple inheritance is not allowed in Ruby. You can include multiple modules if you wanted to mix-in different functionality into your code. Code that is related with a hierarchical nature should be subclassed (inherited). A class can only have 1 direct parent, but can have lots of ancestors. 5. What is the difference between a Module and a Class? +A class can be instantiated into an object, a module cannot. A module is code that can be used across many classes. + diff --git a/week2/homework/simon_says.rb b/week2/homework/simon_says.rb new file mode 100644 index 0000000..ae9a9bf --- /dev/null +++ b/week2/homework/simon_says.rb @@ -0,0 +1,29 @@ +module SimonSays + + def echo input + input + end + + def shout input + input.upcase! + end + + def repeat(input, n = 2) + with_white_space = input + " " + repeated_input = with_white_space * n + repeated_input.chop + ("#{input} " * n).chop + end + + def start_of_word input, i + input[0,i] + input[0...i] + input.slice(0,i) + input.slice(0...i) + end + + def first_word input + input.split[0] + input.split.first + end +end \ No newline at end of file diff --git a/week2/homework/simon_says_spec.rb b/week2/homework/simon_says_spec.rb index 4e6f5bc..2e587d8 100644 --- a/week2/homework/simon_says_spec.rb +++ b/week2/homework/simon_says_spec.rb @@ -7,7 +7,8 @@ # Hint: We are just calling methods, we are not passing a message to a SimonSays object. it "should echo hello" do - echo("hello").should == "hello" + ret_val = echo "hello" + ret_val.should == "hello" end it "should echo bye" do diff --git a/week3/exercises/funny_thing.rb b/week3/exercises/funny_thing.rb new file mode 100644 index 0000000..4cedfc1 --- /dev/null +++ b/week3/exercises/funny_thing.rb @@ -0,0 +1,6 @@ +module FunnyThing + def initialize thing + puts "Whoa!!" + super + end +end \ No newline at end of file diff --git a/week3/exercises/human.rb b/week3/exercises/human.rb new file mode 100644 index 0000000..f438788 --- /dev/null +++ b/week3/exercises/human.rb @@ -0,0 +1,4 @@ +require_relative 'named_thing.rb' +class Human + include NamedThing +end \ No newline at end of file diff --git a/week3/exercises/monster.rb b/week3/exercises/monster.rb index 013c3d2..2236429 100644 --- a/week3/exercises/monster.rb +++ b/week3/exercises/monster.rb @@ -1,9 +1,12 @@ require './named_thing.rb' +require_relative 'funny_thing.rb' class Monster include NamedThing + include FunnyThing + attr_accessor :vulnerabilities, :dangers attr_reader :nocturnal, :legs - + def initialize(noc, legs, name="Monster", vul = [], dangers = []) super(name) @nocturnal = noc @@ -11,4 +14,22 @@ def initialize(noc, legs, name="Monster", vul = [], dangers = []) @dangers = dangers @legs = legs end -end + + def attack human + "#{name} attacked #{human.name}" + end + +protected + def make_nocturnal + @nocturnal = true + end + +private + def out_put_special_name + puts "My name is #{name}" + end + +public + # more public stuff! + +end diff --git a/week3/exercises/named_thing.rb b/week3/exercises/named_thing.rb index 0f36422..ef567de 100644 --- a/week3/exercises/named_thing.rb +++ b/week3/exercises/named_thing.rb @@ -9,6 +9,7 @@ def say_name "My name is #{@name}" end +private def shout_name @name.upcase end diff --git a/week3/exercises/vampire.rb b/week3/exercises/vampire.rb index 764adf6..e3a97d8 100644 --- a/week3/exercises/vampire.rb +++ b/week3/exercises/vampire.rb @@ -1,6 +1,16 @@ require './monster.rb' class Vampire < Monster def initialize(noc=true, legs=2, name ="Vampire", vul=[:garlic, :sunlight], dangers=[:bites]) - super(noc,legs,name,vul,dangers) + super end + + def attack human + puts "#{human.name}'s blood is tasty!" + super + end + + def turn_nocturanl other_monster + other_monster.make_nocturnal + other_monster.out_put_special_name + end end diff --git a/week3/homework/calculator.rb b/week3/homework/calculator.rb new file mode 100644 index 0000000..d4ff99b --- /dev/null +++ b/week3/homework/calculator.rb @@ -0,0 +1,36 @@ + +# encoding : utf-8 +# Homework Number Three -- UW Ruby Class + +class Calculator + + def sum input + input.inject(0, :+) + end + + def multiply *input + input.flatten.inject(1, :*) + end + + def pow base, exp + base ** exp + #multiply Array.new(exp, base) + exp.times.inject(1){|product| product * base} + end + +# 6 #fac(3) +# n = 3 +# 3 * 2 #fac(3-1) +# n=2 +# 2 * 1 #fac(2-1) +# n=1 +# 1 * 1 #fac(1-1) +# n = 0 +# 1 +# [1,2,3] + def fac n + multiply (1..n).to_a + # return 1 if n.zero? + # n * fac(n-1) + end +end \ No newline at end of file diff --git a/week3/homework/questions.txt b/week3/homework/questions.txt index dfb158d..bfff1e2 100644 --- a/week3/homework/questions.txt +++ b/week3/homework/questions.txt @@ -1,3 +1,4 @@ +Homework Three -- Joseph Simpson -- 10-23-2014 Please Read: - Chapter 6 Standard Types - Review Blocks @@ -5,11 +6,65 @@ Please Read: - Chapter 22 The Ruby Language: basic types (symbols), variables and constants 1. What is a symbol? +<<<<<<< HEAD +A symbol is a basic object type in Ruby. Symbol objects represent names and strings +when they are used by the Ruby interpreter. A symbol object provides a single +reference for a name or string during the program execution. 2. What is the difference between a symbol and a string? +A symbol and a string are different basic types of Ruby objects with different +methods and purposes. They are simply two different object types that do different + things. 3. What is a block and how do I call a block? +In Ruby, a block is a syntax literal for Ruby Proc objects. A block is a set of +instructions between braces, {}, or between do ... end statements. A block is a closure +and provides powerful object scope operations. + +A block may be called in three basic ways: + - { yield } + - { block.call } + - &block 4. How do I pass a block to a method? What is the method signature? +A block is passed to a method by appending a block to a method call. For instance: +def three_times + yield + yield + yield +end + + three_times {puts "Hello"} + +The method signature is: + + three_times {puts "Hello"} + + +5. Where would you use regular expressions? + +You would use regular expressions when you need to do string based pattern matching and +substitution. +======= +A symbol is a static name or identifier. + +2. What is the difference between a symbol and a string? +A string is a collection of characters whereas a symbol is a static identifier. A string is not static no matter what the contents of the string are. So the strings "hello" and "hello" are two different objects, whereas the symbol :hello and :hello are the exact same object. If you think of 1 as a FixNum or fixed number, you can think of the symbol :hello as the "FixStr" or fixed string :hello. + +3. What is a block and how do I call a block? +A block is an anonymous function, or some code snipt that you can define and then call at a later time. To call a block you can use the yield keyword. + +4. How do I pass a block to a method? What is the method signature? +To pass a block to a method you define the block after the method call with either the curly bracket enclosure {} or the do/end syntax. An example of passing a block to the each method of an array: + +my_array.each {|a| puts a} + +Any method in Ruby can take a block. You can explicitly add a block to a method by putting an ampersand & before the variable name in the method definition. An example of this would be: + +def my_method(&my_block) + my_block.call +end 5. Where would you use regular expressions? +Regular expressions are used for pattern matching and replacement with strings. An example would be if I wanted to write a syntax checker for some text that checked if each sentence ended with a period, started with a space and then a capital letter. +>>>>>>> b6be2d1d4a801e94a35593138fd38749f6736800 diff --git a/week4/examples/odd_number.rb b/week4/examples/odd_number.rb new file mode 100644 index 0000000..8c2e2ef --- /dev/null +++ b/week4/examples/odd_number.rb @@ -0,0 +1,17 @@ +class OddNumber + include Comparable + attr_reader :value + + def initialize value + @value = value + end + + def succ + OddNumber.new(@value + 2) + end + + def <=> other_odd_number + value <=> other_odd_number.value + end + +end \ No newline at end of file diff --git a/week4/exercises/timer.rb b/week4/exercises/timer.rb new file mode 100644 index 0000000..bf839fe --- /dev/null +++ b/week4/exercises/timer.rb @@ -0,0 +1,9 @@ +module Timer + + def self.time_code n = 1 + start_time = Time.now + n.times { yield } + Time.now - start_time + end + +end \ No newline at end of file diff --git a/week4/exercises/timer_spec.rb b/week4/exercises/timer_spec.rb new file mode 100644 index 0000000..903848c --- /dev/null +++ b/week4/exercises/timer_spec.rb @@ -0,0 +1,31 @@ +require_relative '../../spec_helper' +require_relative 'timer' + +describe Timer do + + it "should run our code" do + flag = false + Timer.time_code do + flag = true + end + expect(flag).to be true + flag.should eq true + end + + it "should return the run time for our code" do + run_time = Timer.time_code do + sleep(3) + nil + end + run_time.should be_within(0.1).of(3.0) + end + + it "should run our code multiple times" do + count = 0 + Timer.time_code(10) do + count += 1 + end + count.should eq 10 + end + +end \ No newline at end of file diff --git a/week4/homework/questions.txt b/week4/homework/questions.txt index ffaf215..6860fc4 100644 --- a/week4/homework/questions.txt +++ b/week4/homework/questions.txt @@ -1,13 +1,54 @@ + +Joseph J. Simpson Please Read: -Chapter 10 Basic Input and Output -The Rake Gem: http://rake.rubyforge.org/ +Chapter 11 Basic Input and Output +The Rake Gem: http://rake.rubyforge.org/ (no go ) +(used ) https://rubygems.org/gems/rake 1. How does Ruby read files? +Ruby has an IO Object to handle input and output. +The File Object is a subclass of IO that specializes in File input and output. +Ruby reads files using the methods associated with the File class. 2. How would you output "Hello World!" to a file called my_output.txt? +file_name = “my_output.txt” +out_file = File.open(file_name, “w”) +out_file.puts “Hello World!” +out_file.close + + 3. What is the Directory class and what is it used for? +The Directory class in Ruby are objects that represent the directories in host operating file system. Directory class objects have numerous methods that manipulate directories and their contents. + 4. What is an IO object? +A Ruby IO object is created from the IO class which is the basis for all inout and output in Ruby. An IO object is used to support Ruby IO methods and operations. + + +5. What is rake and what is it used for? What is a rake task? + +Ruby rake is a software task management tool. Rake supports the specification of tasks and +their associated dependices as well as the grouping of tasks in a namespace. +A Rake task is the basic unit of work or processing in a Rakefile. + + +Instructor answers: +Please Read: +Chapter 10 Basic Input and Output +The Rake Gem: http://docs.seattlerb.org/rake/ + +1. How does Ruby read files? + Ruby reads files using the built in File class, which is a sub-class of the IO class for managing external streams. +2. How would you output "Hello World!" to a file called my_output.txt? + File.open('my_output.txt', 'w') do |f| + f.puts "Hello World!" + end +3. What is the Directory class and what is it used for? + The Dir class is the built-in Ruby class for understanding and managing file system directories. +4. What is an IO object? + An instance of the IO class is used for streaming input and output data in Ruby. It is the basis for all input and output, like reading and writing to a File. 5. What is rake and what is it used for? What is a rake task? + Rake is Ruby-Make, it is a DSL for task management and used for ordering Ruby code into tasks. A rake task is a grouping of Ruby code to be run with the rake command, and potentially an ordered listing of any dependent tasks. + diff --git a/week4/homework/worker.rb b/week4/homework/worker.rb new file mode 100644 index 0000000..51071d0 --- /dev/null +++ b/week4/homework/worker.rb @@ -0,0 +1,5 @@ +module Worker + def self.work n = 1 + n.times.inject(nil){ yield } + end +end \ No newline at end of file diff --git a/week5/Rakefile.rb b/week5/Rakefile.rb new file mode 100644 index 0000000..27d9dbb --- /dev/null +++ b/week5/Rakefile.rb @@ -0,0 +1,16 @@ +namespace :hi do + + desc "Hello world task" + task :hello do + puts "hello world!" + end + +end + +task :bye do + puts "goodbye world!" +end + +task :hi_bye => [:hello, :bye, :hello] + +task :default => [:hello] \ No newline at end of file diff --git a/week5/examples/Rakefile.rb b/week5/examples/Rakefile.rb new file mode 100644 index 0000000..75882c4 --- /dev/null +++ b/week5/examples/Rakefile.rb @@ -0,0 +1,20 @@ +desc "This is a task that takes command line arguments" +task :task_w_args, [:arg1, :arg2] do |t, args| + puts "Args were: #{args}" +end + +desc "This task sets defaults for its arguments" +task :with_defaults, :name1, :name2 do |t, args| + args.with_defaults(arg1: "hi", arg2: "hello") + puts "Args with defaults were: #{args}" +end + +desc "This task calls another rake task" +task :call_task do + Rake::Task[:task_w_args].invoke(3, 4) +end + +desc "This task passes arguments to dependent tasks" +task :with_args, [:arg1, :arg2] => :task_w_args + + diff --git a/week5/exercises/RAKEFILE.rb b/week5/exercises/RAKEFILE.rb new file mode 100644 index 0000000..418fed9 --- /dev/null +++ b/week5/exercises/RAKEFILE.rb @@ -0,0 +1,48 @@ + + +desc 'Default task' +task :default do + puts "This is the default task" +end + +desc 'Read names and output names to standard out' +task :read_out_names do + open_file do |name| + puts name + end +end + +desc 'Create a class directory' +task :create_dir do + Dir.mkdir "class" unless Dir.exists? "class" +end + +desc "Create student directories" +task :create_student_directories => [:create_dir] do + open_file do |name| + d = "class/#{name.chomp}" + Dir.mkdir( d ) unless Dir.exists? d + end +end + +desc "Cleanup and remove all directories" +task :cleanup_dir => [:create_student_directories] do + open_file do |name| + d = "class/#{name.chomp}" + Dir.rmdir( d ) + end + Dir.rmdir("class") +end + +def open_file file_name = "names" + File.open(file_name) do |f| + f.each do |name| + yield name.chomp + end + end +end + + + + + diff --git a/week5/exercises/Rakefile.rb b/week5/exercises/Rakefile.rb new file mode 100644 index 0000000..f34d568 --- /dev/null +++ b/week5/exercises/Rakefile.rb @@ -0,0 +1,42 @@ +desc "prints all the student names" +task :print_names do + open_file_get_lines do |name| + p name + end +end + +desc "Creates a class directory" +task :create_class_dir do + Dir.mkdir "class" unless Dir.exists? "class" +end + +desc "creates student directories" +task :create_student_dirs => [:create_class_dir] do + open_file_get_lines do |name| + dir = "class/#{name}" + Dir.mkdir(dir) unless Dir.exists? dir + end +end + +desc "removes all the directories and the class directory" +task :clean_up => [:create_student_dirs] do + open_file_get_lines do |name| + dir = "class/#{name}" + Dir.rmdir(dir) + end + Dir.rmdir("class") +end + + +def open_file_get_lines file_name = "names" + File.open(file_name) do |f| + f.each do |name| + yield name.chomp + end + end +end + + + + + diff --git a/week6/exercises/test_gem/jjs_hi-0.0.0.gem b/week6/exercises/test_gem/jjs_hi-0.0.0.gem new file mode 100644 index 0000000..85aa735 Binary files /dev/null and b/week6/exercises/test_gem/jjs_hi-0.0.0.gem differ diff --git a/week6/exercises/test_gem/jjs_hi.gemspec b/week6/exercises/test_gem/jjs_hi.gemspec new file mode 100644 index 0000000..528f337 --- /dev/null +++ b/week6/exercises/test_gem/jjs_hi.gemspec @@ -0,0 +1,12 @@ +Gem::Specification.new do |s| + s.name = 'jjs_hi' + s.version = '0.0.0' + s.date = '2014-11-06' + s.summary = 'Hey!! There' + s.description = 'A simple gem' + s.authors = ["Joseph Simpson"] + s.email = 'jjs0sbw@example.com' + s.files = ["lib/jjs_hi.rb"] + s.homepage = 'http://rubygems.org/gems/jjs_hi' + s.license = 'GPL 3' +end \ No newline at end of file diff --git a/week6/exercises/test_gem/lib/jjs_hi.rb b/week6/exercises/test_gem/lib/jjs_hi.rb new file mode 100644 index 0000000..adee499 --- /dev/null +++ b/week6/exercises/test_gem/lib/jjs_hi.rb @@ -0,0 +1,5 @@ +class Hi + def self.hello + puts "Hello world ... stuff.. you know." + end +end \ No newline at end of file diff --git a/week7/homework/features/step_definitions/pirate_steps.rb b/week7/homework/features/step_definitions/pirate_steps.rb index faf1a7f..cc6a779 100644 --- a/week7/homework/features/step_definitions/pirate_steps.rb +++ b/week7/homework/features/step_definitions/pirate_steps.rb @@ -11,9 +11,11 @@ end Letgoandhaul /^it prints out '(.+)'$/ do |arg| - @result.split("\n ").first.should == arg + #@result.split("\n ").first.should == arg + expect(@result.split("\n ").first).to eq arg end Letgoandhaul /^it also prints '(.+)'$/ do |arg| - @result.split("\n ").last.should == arg + #@result.split("\n ").last.should == arg + expect(@result.split("\n ").last).to eq arg end diff --git a/week7/homework/features/step_definitions/pirate_translator.rb b/week7/homework/features/step_definitions/pirate_translator.rb new file mode 100644 index 0000000..38d169e --- /dev/null +++ b/week7/homework/features/step_definitions/pirate_translator.rb @@ -0,0 +1,15 @@ +class PirateTranslator + + def initialize + @result = 'Ahoy Matey' + end + + def say(message) + puts @result + end + + def translate + @result + "\n Shiber Me Timbers You Scurvey Dogs!!" + end + +end \ No newline at end of file diff --git a/week7/homework/features/step_definitions/tic-tac-toe-steps.rb b/week7/homework/features/step_definitions/tic-tac-toe-steps.rb index a3287c1..230ceec 100644 --- a/week7/homework/features/step_definitions/tic-tac-toe-steps.rb +++ b/week7/homework/features/step_definitions/tic-tac-toe-steps.rb @@ -1,5 +1,7 @@ require 'rspec/mocks/standalone' require 'rspec/expectations' + + Given /^I start a new Tic\-Tac\-Toe game$/ do @game = TicTacToe.new end @@ -9,15 +11,18 @@ end Then /^the computer welcomes me to the game with "(.*?)"$/ do |arg1| - @game.welcome_player.should eq arg1 + #@game.welcome_player.should eq arg1 + expect(@game.welcome_player).to eq arg1 end Then /^randomly chooses who goes first$/ do - [@game.player, "Computer"].should include @game.current_player + #[@game.player, "Computer"].should include @game.current_player + expect([@game.player, "Computer"]).to include(@game.current_player) end Then /^who is X and who is O$/ do - TicTacToe::SYMBOLS.should include @game.player_symbol, @game.computer_symbol + #TicTacToe::SYMBOLS.should include @game.player_symbol, @game.computer_symbol + expect(TicTacToe::SYMBOLS).to include(@game.player_symbol, @game.computer_symbol) end Given /^I have a started Tic\-Tac\-Toe game$/ do @@ -26,16 +31,19 @@ end Given /^it is my turn$/ do - @game.current_player.should eq "Renee" + #@game.current_player.should eq "Renee" + expect(@game.current_player).to eq "Renee" end Given /^the computer knows my name is Renee$/ do - @game.player.should eq "Renee" + #@game.player.should eq "Renee" + expect(@game.player).to eq "Renee" end Then /^the computer prints "(.*?)"$/ do |arg1| @game.should_receive(:puts).with(arg1) - @game.indicate_palyer_turn + #expect(@game.should_receive(:puts).with(arg1) + @game.indicate_player_turn end Then /^waits for my input of "(.*?)"$/ do |arg1| @@ -43,7 +51,7 @@ @game.get_player_move end -Given /^it is the computer's turn$/ do +Given /^it is the computers turn$/ do @game = TicTacToe.new(:computer, :O) @game.current_player.should eq "Computer" end diff --git a/week7/homework/features/step_definitions/tic_tac_toe.rb b/week7/homework/features/step_definitions/tic_tac_toe.rb new file mode 100644 index 0000000..8ca79f0 --- /dev/null +++ b/week7/homework/features/step_definitions/tic_tac_toe.rb @@ -0,0 +1,32 @@ +#UW Ruby class Fall 2014 joseph Simpson +class TicTacToe + SYMBOLS = [:X, :O] + attr_accessor :player + + def initialize(player = nil, player_symbol=nil) + @player = player + @player_symbol = player_symbol + @board + end + + def welcome_player + "Welcome #{@player}" + end + + def current_player + @player + end + + def player_symbol + SYMBOLS[0] + end + + def computer_symbol + SYMBOLS[1] + end + + def indicate_player_turn + puts "#{@player}' Turn" + end + +end \ No newline at end of file diff --git a/week7/homework/questions.txt b/week7/homework/questions.txt index d55387d..13dec01 100644 --- a/week7/homework/questions.txt +++ b/week7/homework/questions.txt @@ -1,9 +1,35 @@ - +Joseph Simpson -- 11-20-2014 Please Read Chapters 23 and 24 DuckTyping and MetaProgramming Questions: 1. What is method_missing and how can it be used? -2. What is and Eigenclass and what is it used for? Where Do Singleton methods live? -3. When would you use DuckTypeing? How would you use it to improve your code? -4. What is the difference between a class method and an instance method? What is the difference between instance_eval and class_eval? +A missing_method is a Ruby method that can be called from within the interpreter +when a specific event happens (like missing method). The missing_method method can +be used as a call back to execute code when the event happens. Missing_method may +also be used to dynamically create object attributes by assignment. + +2. What is and Eigenclass and what is it used for? +An Eigenclass is an anonymous, dynamically generated class. This class may be inserted into the Ruby method lookup hierarchy. The Eigenclass is used to store and manage the objects singleton methods. + +Where Do Singleton methods live? In the Eigenclass. + +3. When would you use DuckTypeing? +Ducktyping is good for building flexible tests. +Ducktyping is also good for flexible code interface development. +How would you use it to improve your code? +Write flexible code that is not constrained by specific object types. +Focus on what the code does not what the code is. + +4. What is the difference between a class method and an instance method? +Instance methods are called on an instance of a class. +Class methods are called on a class (self.foo). + +What is the difference between instance_eval and class_eval? +Instance_eval defines class methods. +Class_eval defines instance methods. + 5. What is the difference between a singleton class and a singleton method? +A Ruby singleton class and a metaclass are the same thing. +A Ruby singleton class can not have instances of the singleton class. +A Ruby singleton method is available only for a specific instance of a class (object). + diff --git a/week7/homework/spec_helper.rb b/week7/homework/spec_helper.rb new file mode 100644 index 0000000..1f04ea1 --- /dev/null +++ b/week7/homework/spec_helper.rb @@ -0,0 +1,8 @@ +RSpec.configure do |config| + config.expect_with :rspec do |c| + c.syntax = [:should, :expect] + end + config.mock_with :rspec do |mocks| + mocks.syntax = [:should, :expect] + end +end \ No newline at end of file diff --git a/week7/homework/play_game.rb b/week7/play_game.rb similarity index 87% rename from week7/homework/play_game.rb rename to week7/play_game.rb index 0535830..69d8d97 100644 --- a/week7/homework/play_game.rb +++ b/week7/play_game.rb @@ -1,4 +1,4 @@ -require './features/step_definitions/tic-tac-toe.rb' +require './features/step_definitions/tic-tac-toe-steps.rb' @game = TicTacToe.new puts "What is your name?" diff --git a/week8/exercises/couch.rb b/week8/exercises/couch.rb index b32ea96..3c220eb 100644 --- a/week8/exercises/couch.rb +++ b/week8/exercises/couch.rb @@ -9,7 +9,11 @@ def initialize pillows, cushions, dogs define_method("how_many_#{s}?") do instance_variable_get("@#{s}").count end - end + end + + [:pillows, :cushions, :dogs].each do |s| + define_method("#{s}.map &:to_s") + end def pillow_colors @pillows.map &:to_s diff --git a/week8/exercises/couch_spec.rb b/week8/exercises/couch_spec.rb index 8af3ee0..19c84ce 100644 --- a/week8/exercises/couch_spec.rb +++ b/week8/exercises/couch_spec.rb @@ -1,3 +1,4 @@ +require_relative '../../spec_helper.rb' require_relative 'couch.rb' describe Couch do