diff --git a/Mastermind/mastermind.rb b/Mastermind/mastermind.rb new file mode 100644 index 0000000..a749dd5 --- /dev/null +++ b/Mastermind/mastermind.rb @@ -0,0 +1,77 @@ +class Mastermind + + COLORS = ['Red', 'Blue', 'Green', 'Yellow', 'Periwinkle', 'Egg Shell', 'Chartreuse'] + + def initialize + @guess = [] + #randomly choose 4 colors from COLORS + @secret_code = COLORS.shuffle[0,4] + @game_over = false + #@play_again = "Y" + + end + + def play_game + 10.times do |i| + if @game_over == true + play_again + else + #get guess from user + make_guess + #compare guess to code + compare_guess + #print out number of guess left + if @game_over == false + puts "You have #{9 - i} guesses left." + end + end + end + #out of attempts - game over + puts "Game over! The correct code was #{@secret_code.join(', ')}." + play_again + end + + + def make_guess + #prompt user for input + puts "Enter 4 colors, separated by commas. Your choices are: \n #{COLORS.join(', ')}" + @guess = gets.chomp.split(',') + @guess + end + + def compare_guess + #current_guess = @guess.each_with_index { |c, i| "#{i} #{c}" } + + if exact_match? + puts "Congratulations! You cracked the code." + @game_over = true + #find the matching colors + else + partial_match = [] + @guess.each do |c| + if @secret_code.include?(c) + partial_match << c + end + end + #tell the user which colors they had in the wrong spots + puts "You had #{partial_match.length} out of 4 colors correct" + end + partial_match + end + + def exact_match? + @guess == @secret_code + end + + def play_again + puts "Play again? Enter 'y' or 'n'" + @play_again = gets.chomp + if @play_again == "y" + @game_over = false + play_game + else + puts "Thanks for playing!" + end + end + +end \ No newline at end of file diff --git a/TicTacToe/features/step_definitions/tic-tac-toe-steps.rb b/TicTacToe/features/step_definitions/tic-tac-toe-steps.rb new file mode 100644 index 0000000..c4acdda --- /dev/null +++ b/TicTacToe/features/step_definitions/tic-tac-toe-steps.rb @@ -0,0 +1,124 @@ +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| + expect(@game.welcome_player).to eq arg1 +end + +Then /^randomly chooses who goes first$/ do + expect([@game.player, "Computer"]).to include @game.current_player +end + +Then /^who is X and who is O$/ do + 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 + expect(@game.current_player).to eq "Renee" +end + +Given /^the computer knows my name is Renee$/ do + expect(@game.player).to eq "Renee" +end + +Then /^the computer prints "(.*?)"$/ do |arg1| + @game.should_receive(:puts).with(arg1) + @game.indicate_player_turn +end + +Then /^waits for my input of "(.*?)"$/ do |arg1| + @game.should_receive(:gets).and_return(arg1) + @game.get_player_move +end + +Given /^it is the computers turn$/ do + @game = TicTacToe.new(:computer, :O) + 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 + expect(open_spots).to include(@com_move) +end + +Given /^the computer is playing X$/ do + expect(@game.computer_symbol).to eq :X +end + +Then /^the board should have an X on it$/ do + @game.current_state.should include 'X' +end + +Given /^I am playing X$/ do + @game = TicTacToe.new(:player, :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.player_move).to eq arg1.to_sym +end + +When /^"(.*?)" is not taken$/ do |arg1| + expect(@old_pos).to eq " " +end + +Then /^it is now the computer's turn$/ do + @game.current_player.should eq "Computer" +end + +When /^there are three X's in a row$/ do + @game = TicTacToe.new(:computer, :X) + @game.board[:C1] = @game.board[:B2] = @game.board[:A3] = :X +end + +Then /^I am declared the winner$/ do + @game.determine_winner + expect(@game.player_won?).to be_true +end + +Then /^the game ends$/ do + 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 +end + +Then /^the game is declared a draw$/ do + 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) + @game.player_move.should eq arg1.to_sym +end diff --git a/TicTacToe/features/tic-tac-toe.feature b/TicTacToe/features/tic-tac-toe.feature new file mode 100644 index 0000000..6f3134d --- /dev/null +++ b/TicTacToe/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/TicTacToe/features/tic-tac-toe.rb b/TicTacToe/features/tic-tac-toe.rb new file mode 100644 index 0000000..45dd4ce --- /dev/null +++ b/TicTacToe/features/tic-tac-toe.rb @@ -0,0 +1,212 @@ +class TicTacToe + + attr_accessor :player, :computer, :player_symbol, :computer_symbol, :current_player, :get_player_move + + SYMBOLS = [:X, :O] + + #all combinations of winning moves + @winning_combinations = [ + [:A1, :A2, :A3], + [:B1, :B2, :B3], + [:C1, :C2, :C3], + [:A1, :B2, :C3], + [:A1, :B1, :C1], + [:A2, :B2, :C2], + [:A3, :B3, :C3], + [:A3, :B2,:C1] + ] + + def initialize *players + #check who is playing + if players.length >= 1 + if players[0] == :player + @current_player = "player" + if players[1] == SYMBOLS[0] + @player_symbol = SYMBOLS[0] + @computer_symbol = SYMBOLS[1] + else + @player_symbol = SYMBOLS[1] + @computer_symbol = SYMBOLS[0] + end + else + players[0] == :computer + @current_player = "Computer" + if players[1] == SYMBOLS[0] + @computer_symbol = SYMBOLS[0] + @player_symbol = SYMBOLS[1] + else + @computer_symbol = SYMBOLS[1] + @player_symbol = SYMBOLS[0] + end + end + else + #randomly choose first player + if rand(2) == 1 + @current_player = "player" + @computer = "Computer" + else + @current_player = "Computer" + @player = "player" + end + + #randomly assign who is X and who is O + @player_symbol = SYMBOLS[rand(2)] + if @player_symbol == SYMBOLS[0] + @computer_symbol = SYMBOLS[1] + else + @computer_symbol = SYMBOLS[0] + end + end + + #initialize a blank board + @board = board + @open_spots = open_spots + #since game just started, set over and draw to false + @over = false + @draw = false + end + + def board + #initialize a blank 3x3 board + @board = { + :A1 => " ", :A2 => " ", :A3 => " ", + :B1 =>" ", :B2 => " ", :B3 => " ", + :C1 => " ", :C2 => " ", :C3 => " " + } + end + + def open_spots + #start with an empty board + @open_spots = [ + :A1, :A2, :A3, + :B1, :B2, :B3, + :C1, :C2, :C3 + ] + end + + def computer + @computer = "Computer" + end + + def player= name + @player = name #:player + end + + def welcome_player + return "Welcome #{@player}" + end + + #moved into initialize method since we only want to do this when we start up the game + #def player_symbol + #@player_symbol = SYMBOLS[rand(2)] + #end + + #moved into initialize method since we only want to do this when we start up the game + #def compter_symbol + #if @player_symbol == :X + # @computer_symbol = :O + #else + # @computer_symbol = :X + #end + #end + + def current_player + if @current_player == "player" + @current_player = @player + else + @current_player = "Computer" + end + end + + def indicate_player_turn + puts "#{@player}'s Move:" + end + + def get_player_move + player_move = gets.chomp + return player_move + end + + def player_move + #get move + move = get_player_move.to_sym + + #test if spot is open + #keep asking for a new move until have an open spot + until (@board[move] == " ") + puts "Sorry, that spot is already taken. Please enter another move" + #ask for another move + indicate_player_turn + get_player_move + end + + # if @board[move] == " " + # #update board with player's symbol + # @board[move] = @player_symbol + # #return the move + # move + # else + # puts "Sorry, that spot is already taken. Please enter another move" + # move = get_player_move + # player_move + # end + + #update board with player symbol + @board[move] = @player_symbol + update_open_spots + #set up next turn for Computer + @current_player = "Computer" + move + end + + def computer_move + #find random open_spot + comp_move = open_spots.shuffle.sample + #update board + board[comp_move] = @computer_symbol + @current_player = @computer + end + + def update_open_spots + @board.map {|k,v| @open_spots << k if @board[k] == " "} + #@open_spots + end + + #return the current values in the board hash + def current_state + #current_board + @board.map {|k,v| v.to_s } #@board.values.each { |v| v.to_s} + + end + + #print current game board to screen + def print_current_state + print "#{@board[:A1]} | #{@board[:A2]} | #{@board[:A3]} \n #{@board[:B1]} | #{@board[:B2]} | ##{@board[:B3]}\n #{@board[:C1]} | #{@board[:C2]} | #{@board[:C3]}" + end + + def determine_winner + #if + end + + def spots_open? + @board.has_value?(" ") + end + + def over? + spots_open? + end + + #Answer set tests + def answer_sets + #split the board into :X and :O sets + #x_spaces = @board.map {|k,v| k if v == :X} + #o_spaces = @board.map {|k,v| k if v == :O} + #check if the :X or :O spaces match any of the winning_combination + + # spell out every combo and compare board to it + row_a = + + end + + +end diff --git a/TicTacToe/play_game.rb b/TicTacToe/play_game.rb new file mode 100644 index 0000000..7b99f10 --- /dev/null +++ b/TicTacToe/play_game.rb @@ -0,0 +1,22 @@ +require './features/step_definitions/tic-tac-toe.rb' + +@game = TicTacToe.new +puts "What is your name?" +@game.player = gets.chomp +puts @game.welcome_player + +until @game.over? + case @game.current_player + when "Computer" + @game.computer_move + when @game.player + @game.indicate_player_turn + @game.player_move + end + puts @game.current_state + @game.determine_winner +end + +puts "You Won!" if @game.player_won? +puts "I Won!" if @game.computer_won? +puts "DRAW!" if @game.draw? diff --git a/masterdlymind/.gitignore b/masterdlymind/.gitignore new file mode 100644 index 0000000..34d596d --- /dev/null +++ b/masterdlymind/.gitignore @@ -0,0 +1,22 @@ +<<<<<<< HEAD +/.bundle/ +/.yardoc +/Gemfile.lock +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ +*.bundle +*.so +*.o +*.a +mkmf.log +======= +.DS_Store +/*/.DS_Store +/*/*/.DS_Store +.ruby-version +.ruby-gemset +>>>>>>> 680ed0a642105706e0b3b06294d3596ccbe441fd diff --git a/masterdlymind/Gemfile b/masterdlymind/Gemfile new file mode 100644 index 0000000..70730e5 --- /dev/null +++ b/masterdlymind/Gemfile @@ -0,0 +1,4 @@ +source 'https://rubygems.org' + +# Specify your gem's dependencies in masterdlymind.gemspec +gemspec diff --git a/masterdlymind/LICENSE b/masterdlymind/LICENSE new file mode 100644 index 0000000..0b655e2 --- /dev/null +++ b/masterdlymind/LICENSE @@ -0,0 +1,216 @@ +<<<<<<< HEAD +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright 2012 Renée Hendricksen + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +======= +The MIT License (MIT) + +Copyright (c) 2014 Emily + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +>>>>>>> 0773086cf703f1c4c97ebb9017a2eb09bade7eda diff --git a/masterdlymind/LICENSE.txt b/masterdlymind/LICENSE.txt new file mode 100644 index 0000000..69fdde2 --- /dev/null +++ b/masterdlymind/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright (c) 2014 Emily Ruf + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/masterdlymind/README.md b/masterdlymind/README.md new file mode 100644 index 0000000..8675f07 --- /dev/null +++ b/masterdlymind/README.md @@ -0,0 +1,111 @@ +<<<<<<< HEAD +<<<<<<< HEAD +# Masterdlymind + +TODO: Write a gem description + +## Installation + +Add this line to your application's Gemfile: + +```ruby +gem 'masterdlymind' +``` + +And then execute: + + $ bundle + +Or install it yourself as: + + $ gem install masterdlymind + +## Usage + +TODO: Write usage instructions here + +## Contributing + +1. Fork it ( https://github.com/[my-github-username]/masterdlymind/fork ) +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Commit your changes (`git commit -am 'Add some feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create a new Pull Request +======= +RubyFall2014 +============ + +Course Materials for the Ruby Continuing Education Certificate Program Fall 2014 Quarter + +Syllabus +============ + +Week 1 +* Setup +* Git +* rSpec + +Week 2 +* Strings +* Variables +* Classes and Objects + +Week 3 +* Array and hash +* Numbers / range +* Modules / inheritance + +Week 4 +* Range +* Symbols +* Control +* Blocks + +Week 5 +* Regexp +* I/O +* Files / Dir +* Rake + +Week 6 +* Projects intro +* Gems +* CI + +Week 7 +* Mid-term due! +* Cucumber +* Testing frameworks + +Week 8 +* Metaprogramming +* Duck typing +* Monkey patching + +Week 9 +* Exceptions +* Refactoring +* Review + +Week 10 +* Final due! +* Project due! +* Interesting Stuff + + +Gem Project Requirements +* Make a Gem! +* Source on Github +* Gem Released on RubyGems.org +* Full Documentation and Tests +* OSS License of your choice +* Tested on Travis CI (Bonus: Code Climate!) +* Ready to demo the last day of class + +>>>>>>> 680ed0a642105706e0b3b06294d3596ccbe441fd +======= +masterdlymind +============= + +Play a game of Mastermind +>>>>>>> 0773086cf703f1c4c97ebb9017a2eb09bade7eda diff --git a/masterdlymind/Rakefile b/masterdlymind/Rakefile new file mode 100644 index 0000000..7020018 --- /dev/null +++ b/masterdlymind/Rakefile @@ -0,0 +1,4 @@ +require "bundler/gem_tasks" + +Dir.glob('tasks/**/*.rake').each(&method(:import)) + diff --git a/masterdlymind/lib/masterdlymind.rb b/masterdlymind/lib/masterdlymind.rb new file mode 100644 index 0000000..8c5f4b7 --- /dev/null +++ b/masterdlymind/lib/masterdlymind.rb @@ -0,0 +1,79 @@ +class Masterdlymind + + attr_accessor :secret_code, :guess, :game_over, :play_again + + COLORS = ['Red', 'Blue', 'Green', 'Yellow', 'Periwinkle', 'Egg Shell', 'Chartreuse'] + + def initialize + @guess = [] + #randomly choose 4 colors from COLORS + @secret_code = COLORS.shuffle[0,4] + @game_over = false + #@play_again = "Y" + + end + + def play_game + 10.times do |i| + if @game_over == true + play_again + else + #get guess from user + make_guess + #compare guess to code + compare_guess + #print out number of guess left + if @game_over == false + puts "You have #{9 - i} guesses left." + end + end + end + #out of attempts - game over + puts "Game over! The correct code was #{@secret_code.join(', ')}." + play_again + end + + + def make_guess + #prompt user for input + puts "Enter 4 colors, separated by commas. Your choices are: \n #{COLORS.join(', ')}" + @guess = gets.chomp.split(',') + @guess + end + + def compare_guess + #current_guess = @guess.each_with_index { |c, i| "#{i} #{c}" } + + if exact_match? + puts "Congratulations! You cracked the code." + @game_over = true + #find the matching colors + else + partial_match = [] + @guess.each do |c| + if @secret_code.include?(c) + partial_match << c + end + end + #tell the user which colors they had in the wrong spots + puts "You had #{partial_match.length} out of 4 colors correct" + end + partial_match + end + + def exact_match? + @guess == @secret_code + end + + def play_again + puts "Play again? Enter 'y' or 'n'" + @play_again = gets.chomp + if @play_again == "y" + @game_over = false + play_game + else + puts "Thanks for playing!" + end + end + +end \ No newline at end of file diff --git a/masterdlymind/lib/masterdlymind/version.rb b/masterdlymind/lib/masterdlymind/version.rb new file mode 100644 index 0000000..8ea6e02 --- /dev/null +++ b/masterdlymind/lib/masterdlymind/version.rb @@ -0,0 +1,3 @@ +module Masterdlymind + VERSION = "0.0.1" +end diff --git a/masterdlymind/masterdlymind.gemspec b/masterdlymind/masterdlymind.gemspec new file mode 100644 index 0000000..8dccf38 --- /dev/null +++ b/masterdlymind/masterdlymind.gemspec @@ -0,0 +1,24 @@ +# coding: utf-8 +lib = File.expand_path('../lib', __FILE__) +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) +require 'masterdlymind/version' + +Gem::Specification.new do |spec| + spec.name = "masterdlymind" + spec.version = Masterdlymind::VERSION + spec.authors = ["Emily Ruf"] + spec.email = ["emxruf@gmail.com"] + spec.summary = %q{Play a simple game of Mastermind} + spec.description = %q{Match your wits against the computer in this Ruby implementation of the pattern-guessing game MasterMind} + spec.homepage = "" + spec.license = "MIT" + + spec.files = `git ls-files -z`.split("\x0") + spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } + spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) + spec.require_paths = ["lib"] + + spec.add_development_dependency "bundler", "~> 1.7" + spec.add_development_dependency "rake", "~> 10.0" + spec.add_development_dependency 'rspec' +end diff --git a/masterdlymind/resources.md b/masterdlymind/resources.md new file mode 100644 index 0000000..61730bc --- /dev/null +++ b/masterdlymind/resources.md @@ -0,0 +1,62 @@ +####General +[Our Github repo](https://github.com/UWE-Ruby/RubyWinter2014) + +[Our chat room](https://uweruby.hipchat.com) + +####Week 1: Setup, Git, rSpec +Class slides (coming soon!) + +[Free Online Text-Book](http://www.ruby-doc.org/docs/ProgrammingRuby/) (older edition, but should be fine for this week's reading.) + +[Rspec Matchers](http://rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers) + +[Svn to Git Crash Course](http://git.or.cz/course/svn.html) - if you are switching to Git from Subversion + +[Git Immersion](http://gitimmersion.com/)- general Git course + +[ANSICON Instructions from Price](http://qastuffs.blogspot.com/2011/02/how-to-install-ansicon-for-cucumber-to.html) + +[Command line basics](http://linuxbloggen.dk/wp-content/gallery/cheat-sheets/clicommandsfull.jpg) + +####Week 2: Strings, Variables, Classes, and Objects +[Ruby Docs](http://www.ruby-doc.org/core-1.9.3/String.html) + +[Pragmatic Programmers Guide](http://pragprog.com/book/ruby3/programming-ruby-1-9) (at the bottom is the link to the extending Ruby pdf I mentioned) + +[Travis CI](https://travis-ci.org) (where open source projects are tested) + +[grb](https://github.com/jinzhu/grb) + +[The Ruby ToolBox](https://www.ruby-toolbox.com/) + +####Week 3: Array and hash, Numbers / range, Modules / inheritance +[Enumerable](http://ruby-doc.org/core-1.9.3/Enumerable.html) + +[BigDecimal](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/bigdecimal/rdoc/BigDecimal.html) + +[Array](http://www.ruby-doc.org/core-1.9.3/Array.html) + +[Hash](http://www.ruby-doc.org/core-1.9.3/Hash.html) + +[Range](http://ruby-doc.org/core-1.9.3/Range.html) + +[Why's Poignant Guide](http://mislav.uniqpath.com/poignant-guide/) + +####Week 4: Range, Symbols, Blocks, Control +[Blocks, Procs, Lambdas, and Closures](http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/) + +####Week 5: Regexp, I/O, Files/Dir, Rake +[Rubular](http://www.rubular.com/) +[ASCII Table](http://www.asciitable.com/) + +[Breaking up Regular expressions](http://stackoverflow.com/questions/3833787/making-a-small-regular-expression-a-bit-more-readable) + +####Week 6: Gems, CI + +####Week 7: Cucumber, Testing frameworks, Refactoring + +####Week 8: Metaprogramming, Duck typing, Monkey patching + +####Week 9: Review, Exceptions + +####Week 10: Interesting Stuff... diff --git a/masterdlymind/rspec/masterdlymind_spec.rb b/masterdlymind/rspec/masterdlymind_spec.rb new file mode 100644 index 0000000..601faaa --- /dev/null +++ b/masterdlymind/rspec/masterdlymind_spec.rb @@ -0,0 +1,59 @@ +require 'spec_helper' +require_relative '../lib/masterdlymind' + +describe Masterdlymind do + + before :all do + @game = Masterdlymind.new + end + + describe '#initialize' do + it 'starts a new game by creating an instance ofMasterdlymind' do + @game.should be_an_instance_of Masterdlymind + end + + it 'has a secret code with 4 elements' do + expect(@game.secret_code.length).to eq 4 + end + + it 'has an empty array to hold guesses' do + expect(@game.guess).to be_empty + end + + it 'the game is not set to game over when first started' do + expect(@game.game_over).to eq false + end + + end + + describe '#compare_guess' do + it "compares a user's guess to the secret code and returns how many are matching" do + @game.guess = ["Blue", "Red", "Periwinkle", "Green"] + @game.secret_code = ["Blue", "Red", "Periwinkle", "Yellow"] + expect(@game.compare_guess.length).to eq 3 + end + + it "compares a user's guess and ends the game if the code matches" do + @game.guess = ["Blue", "Red", "Periwinkle", "Green"] + @game.secret_code = ["Blue", "Red", "Periwinkle", "Green"] + @game.compare_guess + expect(@game.game_over).to eq true + end + + end + + describe '#exact_match' do + it 'recognizes when the user guess and the secret code are an exact match' do + expect(@game.exact_match?).to eq true + end + end + + #describe '#play_again' do + # it 'sets game over to false if the user wants to play again' do + # @game.play_again + # @game.play_again = 'y' + # expect(@game.game_over).to eq false + # end + #end + +end \ No newline at end of file diff --git a/masterdlymind/rspec/spec_helper.rb b/masterdlymind/rspec/spec_helper.rb new file mode 100644 index 0000000..1603683 --- /dev/null +++ b/masterdlymind/rspec/spec_helper.rb @@ -0,0 +1,89 @@ +# This file was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause this +# file to always be loaded, without a need to explicitly require it in any files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need it. +# +# The `.rspec` file also contains a few flags that are not defaults but that +# users commonly want. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # These two settings work together to allow you to limit a spec run + # to individual examples or groups you care about by tagging them with + # `:focus` metadata. When nothing is tagged with `:focus`, all examples + # get run. + config.filter_run :focus + config.run_all_when_everything_filtered = true + + # Limits the available syntax to the non-monkey patched syntax that is recommended. + # For more details, see: + # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax + # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = 'doc' + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/masterdlymind/spec_helper.rb b/masterdlymind/spec_helper.rb new file mode 100644 index 0000000..0f63c0c --- /dev/null +++ b/masterdlymind/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 + end +end \ No newline at end of file diff --git a/masterdlymind/tasks/rspec.rake b/masterdlymind/tasks/rspec.rake new file mode 100644 index 0000000..ba8c512 --- /dev/null +++ b/masterdlymind/tasks/rspec.rake @@ -0,0 +1,3 @@ +require 'rspec/core/rake_task' + +RSpec::Core::RakeTask.new(:spec) \ No newline at end of file diff --git a/midterm/instructions_and_questions.txt b/midterm/instructions_and_questions.txt deleted file mode 100644 index a038c9d..0000000 --- a/midterm/instructions_and_questions.txt +++ /dev/null @@ -1,39 +0,0 @@ -Instructions for Mid-Term submission and Git Review (10pts): - - Create a git repository for your answers - - Add and Commit as you work through the questions and programming problems - - Your git log should reflect your work, don't just commit after you have finished working - - Use .gitignore to ignore any files that are not relevant to the midterm - - E-mail me your ssh public key - - I will email you back with your repository name - - Add a remote to your git repository: git@reneedv.com:RubyFall2014/YOURREPOSITORYNAME.git - - Push your changes to the remote - - After 6pm Thursday November 13th you will not be able to push to your remote repository (or clone). - - Questions (20pts): - - What are the three uses of the curly brackets {} in Ruby? - - What is a regular expression and what is a common use for them? - - What is the difference between how a String, a symbol, a FixNum, and a Float are stored in Ruby? - - Are these two statements equivalent? Why or Why Not? - 1. x, y = "hello", "hello" - 2. x = y = "hello" -- What is the difference between a Range and an Array? -- Why would I use a Hash instead of an Array? -- What is your favorite thing about Ruby so far? -- What is your least favorite thing about Ruby so far? - - Programming Problems (10pts each): - - Write a passing rspec file called even_number_spec.rb that tests a class called EvenNumber. - - The EvenNumber class should: - - Only allow even numbers - - Get the next even number - - Compare even numbers - - Generate a range of even numbers -- Make the rspec tests in wish_list_spec.rb pass by writing a WishList class - - The WishList class should: - - Mixin Enumerable - - Define each so it returns wishes as strings with their index as part of the string - -Mid-Term Spec (50pts): -- Make the tests pass. - - diff --git a/midterm/mid_term_spec.rb b/midterm/mid_term_spec.rb deleted file mode 100644 index 87e5c74..0000000 --- a/midterm/mid_term_spec.rb +++ /dev/null @@ -1,75 +0,0 @@ -require_relative '../../spec_helper.rb' -require "#{File.dirname(__FILE__)}/turkey" - -describe Turkey do - - before do - @turkey = Turkey.new(10) - end - - it "should report the turkey weight" do - @turkey.weight.should equal 10 - end - - it "should be a kind of animal" do - @turkey.kind_of?(Animal).should be_true - end - - it "should gobble speak" do - @turkey.gobble_speak("Hello I Am a Turkey. Please Don't Eat Me.").should eq "Gobble Gobble Gobble gobble Gobble. Gobble Gobb'le Gobble Gobble." - end - -end - -require "#{File.dirname(__FILE__)}/thanksgiving_dinner" - -describe ThanksgivingDinner do - - before do - @t_dinner = ThanksgivingDinner.new(:vegan) - @t_dinner.guests = ["Aunt Petunia", "Uncle Vernon", "Aunt Marge", "Dudley", "Harry"] # I know I just made a British family celebrate Thanksgiving, but it could be worse: It could have been the 4th of July! :) - end - - it "should be a kind of dinner" do - @t_dinner.kind_of?(Dinner).should be_true - end - - # Use inject here - it "should sum the letters in each guest name for the seating chart size" do - @t_dinner.seating_chart_size.should eq 45 - end - - it "should provide a menu" do - @t_dinner.respond_to?(:menu).should be_true - end - - context "#menu" do - - it "should have a diet specified" do - @t_dinner.menu[:diet].should eq :vegan - end - - it "should have proteins" do - @t_dinner.menu[:proteins].should eq ["Tofurkey", "Hummus"] - end - - it "should have vegetables" do - @t_dinner.menu[:veggies].should eq [:ginger_carrots , :potatoes, :yams] - end - - # Dinners don't always have dessert, but ThanksgivingDinners always do! - it "should have desserts" do - @t_dinner.menu[:desserts].should eq({:pies => [:pumkin_pie], :other => ["Chocolate Moose"], :molds => [:cranberry, :mango, :cherry]}) - end - - end - - # Use String interpolation, collection methods, and string methods for these two examples - it "should return what is on the dinner menu" do - @t_dinner.whats_for_dinner.should eq "Tonight we have proteins Tofurkey and Hummus, and veggies Ginger Carrots, Potatoes, and Yams." - end - - it "should return what is on the dessert menu" do - @t_dinner.whats_for_dessert.should eq "Tonight we have 5 delicious desserts: Pumkin Pie, Chocolate Moose, and 3 molds: Cranberry and Mango and Cherry." - end -end diff --git a/midterm/wish_list_spec.rb b/midterm/wish_list_spec.rb deleted file mode 100644 index 87f2813..0000000 --- a/midterm/wish_list_spec.rb +++ /dev/null @@ -1,18 +0,0 @@ -require "#{File.dirname(__FILE__)}/wish_list" - -describe WishList do - before :each do - @wish_list = WishList.new - @wish_list.wishes = ["Lamborghini", "Corn Starch and Water Moat", "Vegan Bacon Ice Cream", "Rubber Chicken", "Free Tickets to MockingJay"] - end - - it "should mixin Enumerable" do - @wish_list.is_a?(Enumerable).should be_true - end - - context "#each" do - it "should give me a numberd list" do - @wish_list.map{|w| w}.should eq ["1. Lamborghini", "2. Corn Starch and Water Moat", "3. Vegan Bacon Ice Cream", "4. Rubber Chicken", "5. Free Tickets to MockingJay"] - end - end -end \ No newline at end of file diff --git a/week1/examples/.rspec b/week1/examples/.rspec new file mode 100644 index 0000000..83e16f8 --- /dev/null +++ b/week1/examples/.rspec @@ -0,0 +1,2 @@ +--color +--require spec_helper diff --git a/week1/homework/questions.txt b/week1/homework/questions.txt index 2257bb9..520d034 100644 --- a/week1/homework/questions.txt +++ b/week1/homework/questions.txt @@ -3,13 +3,26 @@ Chapter 3 Classes, Objects, and Variables p.86-90 Strings (Strings section in Chapter 6 Standard Types) 1. What is an object? + An object has properties and methods. These properties can be accessed using the methods defined for that object. + 2. What is a variable? + A variable holds a reference to an object (since everything in Ruby is an object). They don;t contain the actual object, just a pointer to where it is stored in memory. There are different types of variables in Ruby (instance, local, global and class variables) that can be used to control the scope of the variable, or what parts of the program have access to that variable. + 3. What is the difference between an object and a class? + Objects can be grouped by Class. For example, a String is an object of the Class String. Classes are like templates for Objects. You use that template when you create a new Object of some Class. + 4. What is a String? - + A String is an object of class String. This data type is a sequence of characters, most often printable characters (like ASCII), but can also contain binary data. In earlier versions of Ruby, Strings were just 8-bit bytes, but now the String data type also knows how it is encoded (e.g. UTF-8). + + 5. What are three messages that I can send to a string object? Hint: think methods + "some string".length => 11 + "some string".capitalize => "Some string" + "some string".reverse => "gnirts emos" + 6. What are two ways of defining a String literal? Bonus: What is the difference between them? + You can define a String literal using double quotes ("") or single quotes ('') as the delimiters at the beginning and end of the String. The main differences are that using double-quotes allows for more escape sequences as well as interpolation. Escape sequences are needed to represent some special characters in strings, such as the newline character, \n. Interpolation lets you insert Ruby values or statements into a string, "That\'s funny, #{'ha'*3}" diff --git a/week1/homework/strings_and_rspec_spec.rb b/week1/homework/strings_and_rspec_spec.rb index 496e61d..3ad990e 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 @@ -12,22 +13,29 @@ describe String do context "When a string is defined" do + #before(:all) >> runs once before everything else runs. Good for if you have setup before(:all) do - @my_string = "Renée is a fun teacher. Ruby is a really cool programming language" + @my_string = "Renee 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 + result = @my_string.length + result.should eq 66 + #expect(@my_string.size).to eq 66 + #@my_string.size.should eq 66 + end - it "should be able to split on the . charater" do - pending - result = #do something with @my_string here + it "should be able to split on the . character" do + result = @my_string.split(/\./) + #result = @my_string.split('.') result.should have(2).items + #rspec calls .items on collection matchers, returns an array 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 + result = @my_string.encoding + result.should eq (Encoding.find("UTF-8")) + #Encoding is a class, has method .find for finding encoding object end end end diff --git a/week2/homework/questions.txt b/week2/homework/questions.txt index 939e42d..daa0296 100644 --- a/week2/homework/questions.txt +++ b/week2/homework/questions.txt @@ -4,10 +4,22 @@ Sharing Functionality: Inheritance, Modules, and Mixins 1. What is the difference between a Hash and an Array? + Both hashes and arrays are indexed collections of object references. The difference is the way they are indexed. Arrays are indexed with integers only (starting at 0), and hashes are indexed using objects of any type. In hashes, the the indexer is called a key and is provided along with the value to store, allowing you to "look up" a value by providing the key. + 2. When would you use an Array over a Hash and vice versa? + Hashes are better suited for times when you want to associate or map two objects to each other, such as a customer and their recent purchases. Arrays might be better to use when you don't want any extra overhead and need to access a collection as efficiently as possible. + 3. What is a module? Enumerable is a built in Ruby module, what is it? + Modules allow you to group together methods, classes and constants. + + Enumerable provides classes with searching and sorting methods using the class's 'each' method. Enumerable can be used on any class that defines an 'each' method and includes the Enumerable module. + 4. Can you inherit more than one thing in Ruby? How could you get around this problem? + Ruby only supports single inheritance, but mixins and modules allow classes to have all the instance methods of that modules, the same way inheritance would. + 5. What is the difference between a Module and a Class? + + A module can't have instances. diff --git a/week2/homework/simon_says.rb b/week2/homework/simon_says.rb new file mode 100644 index 0000000..b829f3d --- /dev/null +++ b/week2/homework/simon_says.rb @@ -0,0 +1,32 @@ +module SimonSays + + #echo takes a greeting and says it back + def echo(greeting) + greeting + end + + #shout takes words and yells them back in ALL CAPS + def shout(words) + words.upcase! + end + + #repeat takes a saying and repeats it at least twice, if no number is specified + def repeat(saying, number=2) + repeat_saying = (saying + " ") * number + repeat_saying.rstrip! + end + + #start_of_word takes a word and returns the letters starting from [0] to the specified number + def start_of_word(word, number) + index = number - 1 + word.slice!(0..index) + end + + #first_word takes a phrase and returns the first word + def first_word(phrase) + phrase_array = phrase.split(' ') + phrase_array[0] + end + + +end \ No newline at end of file diff --git a/week3/exercises/monster.rb b/week3/exercises/monster.rb index 013c3d2..7c53b7a 100644 --- a/week3/exercises/monster.rb +++ b/week3/exercises/monster.rb @@ -11,4 +11,8 @@ def initialize(noc, legs, name="Monster", vul = [], dangers = []) @dangers = dangers @legs = legs end + + def attack human + "#{self.name} attacked #{human.name}" + end end diff --git a/week3/exercises/vampire.rb b/week3/exercises/vampire.rb index 764adf6..3c84971 100644 --- a/week3/exercises/vampire.rb +++ b/week3/exercises/vampire.rb @@ -1,6 +1,10 @@ require './monster.rb' -class Vampire < Monster +class Vampire < Monster # inheriting from monster + #override inherited initialize functionality + #set up logical defaults that are *slightly* different from Monster superclass def initialize(noc=true, legs=2, name ="Vampire", vul=[:garlic, :sunlight], dangers=[:bites]) + #super - call back to Monster superclass. + #call this method (inititalize) on parent class Monster, and use these args (same number, same order, passes args to parent method) super(noc,legs,name,vul,dangers) end end diff --git a/week3/homework/calculator.rb b/week3/homework/calculator.rb new file mode 100644 index 0000000..672ca9f --- /dev/null +++ b/week3/homework/calculator.rb @@ -0,0 +1,38 @@ +class Calculator + + + #computes sum of the array + def sum(array) + #sum = 0 + #array.each do |i| + #sum += i + #end + #sum.to_i + + array.reduce(:+) || 0 + end + + #multiply 2 numbers + def multiply(*array) + #product = 1 + #array.each do |i| + #product *= i + #end + + array = array.flatten + array.reduce(1, :*) + + end + + #raises one num to the power of another num + def pow(base, exponent) + base ** exponent + end + + #Computes factorial of a given num + def fac(num) + array = (1..num) + array.inject(:*) || 1 + end + +end \ No newline at end of file diff --git a/week3/homework/questions.txt b/week3/homework/questions.txt index dfb158d..4d6f033 100644 --- a/week3/homework/questions.txt +++ b/week3/homework/questions.txt @@ -5,11 +5,19 @@ Please Read: - Chapter 22 The Ruby Language: basic types (symbols), variables and constants 1. What is a symbol? + Symbols are identifiers, used to represent names. For example, typing ':color', can be thought of as saying, "the thing named 'color'". 2. What is the difference between a symbol and a string? + Symbols are immutable, meaning they cannot be changed after assignment, only overwritten. Symbols always refer to the same name, unlike strings. If two strings contain the same contents, they still exist as two different objects. 3. What is a block and how do I call a block? + A block is a set of Ruby code (statements or expressions) grouped inside braces or a do...end statement. A block is a closure, meaning it includes context information whenever it is called. This can include the value of 'self', the class variables, local variables and any blocks. 4. How do I pass a block to a method? What is the method signature? + Code blocks within methods can be called using the 'yield' keyword. You can also create a Proc object when you pass a block to a method where the last parameter is prefixed with an ampersand (&). + + The method signature includes the method name and parameters. + 5. Where would you use regular expressions? + A regular expression is a pattern that can be matched against a string. It's useful when you're looking to do some string manipulation such as testing to see if a string matches a given pattern, extracting a string from some text, or making a change to a string following a specified pattern. diff --git a/week4/homework/questions.txt b/week4/homework/questions.txt index ffaf215..904d59e 100644 --- a/week4/homework/questions.txt +++ b/week4/homework/questions.txt @@ -3,11 +3,20 @@ Chapter 10 Basic Input and Output The Rake Gem: http://rake.rubyforge.org/ 1. How does Ruby read files? + Ruby opens an IO stream, in this case it's a channel to a File object, and reads the input line by line. 2. How would you output "Hello World!" to a file called my_output.txt? + File.open("my_output.txt", "w") do |file| + file.puts "Hello World!" + end + 3. What is the Directory class and what is it used for? + The Directory class represents a directory IO stream for accessing file names from the operating system. 4. What is an IO object? + It's the base class for handling input and output. It's a stream between a Ruby program and an external resource, such as an operating system. At the most basic level, you are just reading from and writing to an IO object. The IO object has many subclasses, including File and TCPSocket. + 5. What is rake and what is it used for? What is a rake task? + Rake is a task management tool for Ruby, similar to Make. It can be used to automate common tasks such as compiling files or publishing to FTP sites. A rake task is just a small bit of code that performs some action (usually relating to build automation or another software process), and can be linked to other tasks or dependencies to create an automated workflow. \ No newline at end of file diff --git a/week7/class_materials/cucumber/features/step_definitions/converter.rb b/week7/class_materials/cucumber/features/step_definitions/converter.rb index e37c629..a630eb9 100644 --- a/week7/class_materials/cucumber/features/step_definitions/converter.rb +++ b/week7/class_materials/cucumber/features/step_definitions/converter.rb @@ -9,10 +9,14 @@ def type=(type) end def convert - self.send("#{@type}_convertion") + self.send("#{@type}_conversion") end - def Celsius_convertion + def Celsius_conversion (@unit * (9.0/5.0) + 32.0).round(1) end + + def Fahrenheit_conversion + ((@unit - 32) * (5/9)).round(1) + end end diff --git a/week7/exercises/step_definitions/converter_steps.rb b/week7/exercises/step_definitions/converter_steps.rb new file mode 100644 index 0000000..c085e46 --- /dev/null +++ b/week7/exercises/step_definitions/converter_steps.rb @@ -0,0 +1,17 @@ +Given /^I have entered (\d+) into the converter$/ do | value | + @converter = Converter.new(value) +end + +Given /^I select Farenheit$/ do + @converter.type = "Fahrenheit" +end + +When /^I press convert$/ do + @result = @converter.convert +end + +Then /^the result should be (\d+)\.(\d+) on the screen$/ do |arg1, arg2| + @result.should eq "#{arg1}.#{arg2}".Fahrenheit_conversion +end + + 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..a9bd88e 100644 --- a/week7/homework/features/step_definitions/tic-tac-toe-steps.rb +++ b/week7/homework/features/step_definitions/tic-tac-toe-steps.rb @@ -35,7 +35,7 @@ Then /^the computer prints "(.*?)"$/ do |arg1| @game.should_receive(:puts).with(arg1) - @game.indicate_palyer_turn + @game.indicate_player_turn end Then /^waits for my input of "(.*?)"$/ do |arg1| diff --git a/week7/homework/features/step_definitions/translator.rb b/week7/homework/features/step_definitions/translator.rb new file mode 100644 index 0000000..470b6da --- /dev/null +++ b/week7/homework/features/step_definitions/translator.rb @@ -0,0 +1,9 @@ +class PirateTranslator + + def say word + end + + def translate + result = "Ahoy Matey\n Shiber Me Timbers You Scurvey Dogs!!" + end +end diff --git a/week7/homework/features/tic-tac-toe.rb b/week7/homework/features/tic-tac-toe.rb new file mode 100644 index 0000000..ced9341 --- /dev/null +++ b/week7/homework/features/tic-tac-toe.rb @@ -0,0 +1,44 @@ +class TicTacToe + + attr_accessor :player + + def initialize + end + + def player + #needs to take input from gets.chomp + end + + def welcome_player + puts "Welcome #{@player}" + end + + def current_player + #choose who goes first + #as hash? + end + + def player_symbol + end + + def computer_symbol + end + + def indicate_player_turn + end + + def indicate_player_turn + end + + def open_spots + end + + def computer_move + end + + def current_state + end + + + +end diff --git a/week7/homework/questions.txt b/week7/homework/questions.txt index d55387d..15e37c3 100644 --- a/week7/homework/questions.txt +++ b/week7/homework/questions.txt @@ -3,7 +3,18 @@ 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? + Method_missing is a callback method that gets called when a object tries to call a method that isn't implemented for that object. It's similar to using respond_to? to see if an an object responds to the method you want to send to it. + +2. What is an Eigenclass and what is it used for? Where Do Singleton methods live? + An Eigen class (also known as a singleton class) is an anonymous class created by Ruby for holding the singleton methods defined on an instance of an object. The Eigenclass becomes the object's class, and its original class (for example, String), becomes the superclass. + 3. When would you use DuckTypeing? How would you use it to improve your code? + Duck Typing means not checking the type of arguments or class of objects. This can be done in Ruby because an object's type is determined by what it can do, not by its class. + Using this means you can write simpler 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 class method is defined for that class and can be used in that class or its subclasses. Instance methods are called on instances of classes. + The method instance_eval is used to define a class method, and class_eval is used to define an instance method. + 5. What is the difference between a singleton class and a singleton method? + A singleton method is a method specific to an instance of a class. A singleton class is an anonymous class created by Ruby for implementing a singleton method. The singleton class is the class of the object you are manipulating, and its original class (for example, String), becomes the superclass of the singleton class.