diff --git a/.gitignore b/.gitignore index 18d7cf1..db62a8a 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ test/version_tmp tmp *.*~ *~ +notes # YARD artifacts .yardoc diff --git a/mid_term/questions.txt b/mid_term/questions.txt index 0eba895..800f885 100644 --- a/mid_term/questions.txt +++ b/mid_term/questions.txt @@ -1,4 +1,5 @@ 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 @@ -8,8 +9,7 @@ Instructions for Mid-Term submission and Git Review (10pts): - Add a remote to your git repository: git@nird.us:RubyFall2012/YOURREPOSITORYNAME.git - Push your changes to the remote - After 6pm Tuesday November 13th you will not be able to push to your remote repository (or clone). - - Questions (20pts): +Questions (20pts): - What are the three uses of the curly brackets {} in Ruby? 1. String interpolation: "#{1+1}" 2. Hash instantiation: {:key => "value"} @@ -36,19 +36,18 @@ If I had data which I wanted to reference by meta-data instead of by order I wou .map - What is your least favorite thing about Ruby so far? -nil.object_id => 4 - Programming Problems (10pts each): - - Write a passing rspec file called even_number_spec.rb that tests a class called EvenNumber. - - The EvenNumber class should: +- 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 + -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 +- 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/week1/exercises/roster.txt b/week1/exercises/roster.txt index 8d13804..5a6b764 100644 --- a/week1/exercises/roster.txt +++ b/week1/exercises/roster.txt @@ -1,4 +1,6 @@ name, email, github, twitter, hipchat + + Brian Ward, brianmatthewward@gmail.com, brianward, mrbrianward, brianmatthewward@gmail.com Renee D, renee@nird.us, reneedv, @gigglegirl4e, renee.devoursney@gmail.com Yan Li, leeyeon0307@gmail.com, YanLi0307, nil, leeyeon0307@gmail.com @@ -31,3 +33,4 @@ Price Hardman, PriceHardman@gmail.com, PriceHardman Will Sugg, sugg.will@gmail.com, wsugg, , sugg.will@gmail.com Nicole Lewis, lewis.nicole@gmail.com, nelewis, nil, lewis.nicole@gmail.com Sol Wagner, capnsol@gmail.com, Soladin, n/a, capnsol@gmail.com + diff --git a/week1/exercises/rspec_spec.rb b/week1/exercises/rspec_spec.rb index f4c2f0b..bf5b14a 100644 --- a/week1/exercises/rspec_spec.rb +++ b/week1/exercises/rspec_spec.rb @@ -90,6 +90,5 @@ it "should check basic spelling" do "Field".should include('ie') end - end end diff --git a/week1/homework/questions.txt b/week1/homework/questions.txt index 0adfd69..7446787 100644 --- a/week1/homework/questions.txt +++ b/week1/homework/questions.txt @@ -3,22 +3,22 @@ Chapter 3 Classes, Objects, and Variables p.90-94 Strings 1. What is an object? -An object is a representation in memory of a specific concept or thing that the Ruby interpreter knows about. +=> An object is an abstract data structure combined with functionality (in the form of methods) that allows the data structure to interact and be interacted with. 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. +=> A variable is a named location in memory whose value can be changed. In Ruby, a variable is named reference to an 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). +=> Classes are essentially templates for objects. All of the attributes and properties of an object are determined by the class of which it is an instance. The difference between classes and objects is that a class defines the form and functionality of an object, while an object (or class instance) is an entity that actually posseses the form and functionality described in the class. 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[]). +=> A string is a sequence of characters, usually in the form of readable text. In Ruby, string objects are instances of the String class. 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 +=> a) .length ## returns the length of the string + b) .empty? ## returns true if the string is of length 0, else false. + c) .index("") ## if the character is in the string, returns the index, else nil. 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 qoutes allow for 2 escape characters: \' and \\ . The double qouted 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 qouted string takes up much less memory than a doulbe qouted string with interpolation. Without interpolation, both are about the same. +=> The two ways of creating string literals are enclosing the desired text in either double or single quotes. The difference between the two is the amount of processing Ruby does on the string. With double quotes, more processing is done, such as expression interpolation (e.g. #{name}) and interpreting control characters (e.g. In, "Hello, \nWorld!" \n forces a line break). String literals created with single quotes are treated essentially as-is. For instance, a newline character placed in a string in single quotes would literally be treated as a backslash and an n, rather than forcing a line break. diff --git a/week1/homework/strings_and_rspec_spec.rb b/week1/homework/strings_and_rspec_spec.rb index 2f188f6..0fe7997 100644 --- a/week1/homework/strings_and_rspec_spec.rb +++ b/week1/homework/strings_and_rspec_spec.rb @@ -13,6 +13,9 @@ @my_string = "Renée is a fun teacher. Ruby is a really cool programming language" end it "should be able to count the charaters" do + result = @my_string.length + result.should eq 66 + @my_string.should have(@my_string.size).characters end it "should be able to split on the . charater" do @@ -20,6 +23,9 @@ result.should have(2).items end it "should be able to give the encoding of the string" do + + result = @my_string.encoding + result.should eq (Encoding.find("UTF-8")) @my_string.encoding.should eq (Encoding.find("UTF-8")) end end diff --git a/week2/exercises/book.rb b/week2/exercises/book.rb index 50bc054..cb35c59 100644 --- a/week2/exercises/book.rb +++ b/week2/exercises/book.rb @@ -1,5 +1,12 @@ class Book +<<<<<<< HEAD + attr_reader :title, :pageCount + + def initialize(title, pageCount = "Not Given") + @title = title + @pageCount = pageCount +======= attr_accessor :title, :pages def initialize(title, pages) @@ -9,5 +16,6 @@ def initialize(title, pages) def page_count "Page count is #{@pages}" +>>>>>>> 476e4b543ee68aad8bb809afdfe2207afd39e8e5 end end diff --git a/week2/exercises/mad_libs.rb b/week2/exercises/mad_libs.rb index 3af5583..472c072 100644 --- a/week2/exercises/mad_libs.rb +++ b/week2/exercises/mad_libs.rb @@ -1,10 +1,19 @@ -puts "Please enter a noun" -noun = gets.chomp puts "Please enter an adjective" adjective = gets.chomp +<<<<<<< HEAD +puts "Please enter a plural noun" +plural_noun = gets.chomp +puts "Please enter a present-tense action verb" +verb = gets.chomp +puts "Please enter another present-tense action verb" +another_verb = gets.chomp +story = "Twas #{adjective}, and the slythy #{plural_noun} +Did #{verb} and #{another_verb} in the wabe:" +======= puts "Please enter a past tense action verb" verb_past_tense = gets.chomp puts "What does the #{noun} say?" says = gets.chomp story = "The #{adjective} #{noun} #{verb_past_tense} past the graveyard and says #{says}" +>>>>>>> 476e4b543ee68aad8bb809afdfe2207afd39e8e5 puts story diff --git a/week2/homework/questions.txt b/week2/homework/questions.txt index 4cfc0a3..60c41d5 100644 --- a/week2/homework/questions.txt +++ b/week2/homework/questions.txt @@ -3,16 +3,16 @@ Containers, Blocks, and Iterators Sharing Functionality: Inheritance, Modules, and Mixins 1. What is the difference between a Hash and an Array? -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. +A hash is a non-ordered collection of objects, indexed via a key value that need not (and usually is not) an integer. An array on the other hand is a numerally-indexed collection. 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. +Collections requiring some sort of order are ideal for being placed into an array, whereas a hash is best for collections whose members are referenced by a category (e.g. name: Price Hardman). 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. +A module is code intended to be used by many classes. Modules have many advantages including namespaces, which can keep large programs from getting messy/buggy with regard to variable and method names. Enumerable is a module that provides the ability to traverse and manipulate collections. 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. +Ruby only supports single inheritance. The workaround to this is using modules (of which you can include multiple in a class). 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. +A module defines a namespace in which classes, methods, and constants can be defined. Whereas classes define functionality that can be inherited from parent classes and passed down to child classes, modules define functionality that can included across classes. diff --git a/week2/homework/simon_says.rb b/week2/homework/simon_says.rb index fa35ccd..dd5ea18 100644 --- a/week2/homework/simon_says.rb +++ b/week2/homework/simon_says.rb @@ -8,15 +8,14 @@ def shout(st) end def first_word(st) - st.split.first + st.split(' ')[0] end def start_of_word(st,i) - st[0...i] + st.slice!(0..i-1) end def repeat(st, t=2) - return "Go Away!" if t==0 - ([st]*t).join(' ') + (st+" ")*(t-1)+st # or could use Array join method. end end diff --git a/week3/homework/calculator.rb b/week3/homework/calculator.rb index f8916e3..4c61e87 100644 --- a/week3/homework/calculator.rb +++ b/week3/homework/calculator.rb @@ -1,24 +1,18 @@ class Calculator - def sum(array) - array.inject(0){|sum, x| sum +x} + def sum(input) + input.empty? ? 0 : input.inject(:+) #if input is empty array, return 0, else sum the elements end - def multiply(*numbers) - puts numbers.inspect - numbers.flatten.inject(:*) +<<<<<<< HEAD + def product(*input) #takes multiple arguments, as an array + input.length > 1 ? input.inject(:*) : input[0].inject(:*) end - def pow(base, p) - #(1...p).to_a.inject(base){|r,v| r *= base} - pow_fac(base, p) + def power(base, power) + base**power end - def fac(n) - #(1..n).to_a.inject(1){|f,v| f *= v} - pow_fac(n) + def factorial(n) + n == 0 ? 1 : (n==1 ? 1 : n*factorial(n-1) ) #recursive definition, takes into account zero case using nested ternary end -private - def pow_fac(base=nil, p) - (1..p).to_a.inject(1){|f,v| f *= base || v} - end end diff --git a/week3/homework/calculator_spec.rb b/week3/homework/calculator_spec.rb index 5a418ed..5e513be 100644 --- a/week3/homework/calculator_spec.rb +++ b/week3/homework/calculator_spec.rb @@ -26,20 +26,15 @@ # Once the above tests pass, # write tests and code for the following: - describe "#multiply" do - it "multiplies two numbers" do - @calculator.multiply(2,2).should eq 4 - end - - it "multiplies an array of numbers" do - @calculator.multiply([2,2]).should eq 4 - end - end + it "multiplies two numbers" do + @calculator.product(3,2).should == 6 + end + it "multiplies an array of numbers" do + @calculator.product([3,2,1]).should == 6 + end it "raises one number to the power of another number" do - p = 1 - 32.times{ p *= 2 } - @calculator.pow(2,32).should eq p + @calculator.power(3,2).should == 9 end # http://en.wikipedia.org/wiki/Factorial @@ -62,7 +57,6 @@ it "computes the factorial of 10" do @calculator.fac(10).should eq 3628800 end - end end diff --git a/week3/homework/questions.txt b/week3/homework/questions.txt index 08067b8..04586ab 100644 --- a/week3/homework/questions.txt +++ b/week3/homework/questions.txt @@ -5,24 +5,23 @@ Please Read: - Chapter 22 The Ruby Language: basic types (symbols), variables and constants 1. What is a symbol? -A symbol is a static name or identifier. +=>A symbol is a constant defined by a name following a colon, e.g. :north. The advantage of doing this as opposed to defining a variable is that the value of a symbol is assigned and handled internally by Ruby, leading to greater simplicity and performance. All the user has to do is declare a symbol with a memorable name. 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 ojects, 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. +=>A symbol is a unique numerical value (handled by Ruby under the surface) that is referenced with a string name. A symbol is not an instance of the string class, and thereby has no access to all the methods of String. A symbol can be turned into a string with to_s though. 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. +=> A block is a snippet of code -- enclosed either in braces or do..end -- that is called immediately after the invocation of a method and is used to generalize the functionality of that method. For instance, +array1 = [] +def double(input) + yield(input*2) +end +double(3) {|x| puts "The method output is #{x}"} #prints "The method output is 6". +double(three) {|x| array1 << x} #places output threethree into array1. +Thus, while the functionality of the method double is the same (it simply multiplies its input by 2, according to the defintion of the * operator for the input's class), the block allows that output to be implemented in a wide variety of ways. Blocks are also very convenient for iterating over collections. 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 +=> A block is passed to a method either by using "yield" in the method definition (see previous answer), or as a parameter itself with a leading ampersand (e.g. def method(input, &block) ). 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 sentance ended with a period, started with a space and then a capital letter. +=> Regular expressions are used for parsing strings in powerful and more robust ways than simpler string manipulation techniques allow. One of the many instances in which one could use regular expressions is in processing data read from a file, which would get read by IO as a string. diff --git a/week4/homework/questions.txt b/week4/homework/questions.txt index bc1ab7c..df7eb13 100644 --- a/week4/homework/questions.txt +++ b/week4/homework/questions.txt @@ -3,7 +3,18 @@ Chapter 10 Basic Input and Output The Rake Gem: http://rake.rubyforge.org/ 1. How does Ruby read files? +=> Ruby has an IO object that handles input and output, of which File is a child object. A file can be read by instantiating a File object and passing the filename as a parameter, then using a variety of methods and iterators to process the data as desired. + 2. How would you output "Hello World!" to a file called my_output.txt? +=> File.open('this\is\the\path\to\my_output.txt',"w") do |file| + file.print "Hello, world!" +end + 3. What is the Directory class and what is it used for? +=> The Directory -- or Dir -- class gives a powerful way to navigate and manipulate directories and the contents thereof. It can be used in any situation where it would be useful to change or write to specific directories. + 4. What is an IO object? +=> An IO object is a Ruby object that provides a convenient and safe interface for doing input and output in a variety of contexts, most commonly standard IO and files. File is a child class of IO. + 5. What is rake and what is it used for? What is a rake task? +=> Rake is a gem that provides an environment for managing file dependencies and buidling multi-file projects. It features the functionality of make, but uses Ruby syntax. The operations and functions a user can perform with rake is contained in rake tasks, which are essentially scripts. diff --git a/week7/homework/features/step_definitions/pirate.rb b/week7/homework/features/step_definitions/pirate.rb index d2a6f6a..ad1352f 100644 --- a/week7/homework/features/step_definitions/pirate.rb +++ b/week7/homework/features/step_definitions/pirate.rb @@ -1,3 +1,24 @@ +<<<<<<< HEAD +class PirateTranslator + + def initialize + @translation_buffer = "" + end + + def get_input(input) + @translation_buffer = input + end + + def translate + case @translation + when 'Hello Friend' + output = 'Ahoy Matey' + else + output = 'Avast!' + end + output+'Shiber Me Timbers You Scurvey Dogs!!' + end +======= class PirateTranslator PIRATE_WORDS = { "Hello Friend" => "Ahoy Matey" @@ -14,4 +35,5 @@ def translate def lookup_pirate(str) PIRATE_WORDS[str] end +>>>>>>> 49855ef72d67870e69889977eb388f8994bc02f9 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..b9671f5 100644 --- a/week7/homework/features/step_definitions/pirate_steps.rb +++ b/week7/homework/features/step_definitions/pirate_steps.rb @@ -1,3 +1,24 @@ +<<<<<<< HEAD +Gangway /^I have a PirateTranslator$/ do + @translator = PirateTranslator.new +end + +Blimey /^I say 'Hello Friend'$/ do + @translator.get_input('Hello Friend') +end + +Blimey /^I hit translate$/ do + @translator.translate +end + +Letgoandhaul /^it prints out 'Ahoy Matey'$/ do + @translator.translate.include?('Ahoy Matey') +end + +Letgoandhaul /^it also prints 'Shiber Me Timbers You Scurvey Dogs!!'$/ do + @translator.translate.include?('Shiber Me Timbers You Scurvey Dogs!!') +end +======= Gangway /^I have a (\w+)$/ do |arg| @translator = Kernel.const_get(arg).new end @@ -17,3 +38,4 @@ Letgoandhaul /^it also prints '(.+)'$/ do |arg| @result.split("\n ").last.should == arg end +>>>>>>> 49855ef72d67870e69889977eb388f8994bc02f9 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..39f5a1e --- /dev/null +++ b/week7/homework/features/step_definitions/tic-tac-toe.rb @@ -0,0 +1,196 @@ +class TicTacToe + attr_accessor :board + attr_reader :player, :current_player, :other_player, :player_symbol, :computer_symbol, :SYMBOLS, :current_state, :open_spots + SYMBOLS = [:X,:O] + + def initialize(who_goes_first = nil,player_symbol=nil) #optional arguments: who goes first, and which symbol player has. + + process_optional_arguments(who_goes_first,player_symbol) #private method that decides who goes first and has which + #symbol, depending on optional arguments + + @board = { #initialize the board as empty + :A1 => " ", :A2 => " ", :A3 => " ", + :B1 => " ", :B2 => " ", :B3 => " ", + :C1 => " ", :C2 => " ", :C3 => " " + } + + @open_spots = [:A1,:A2,:A3,:B1,:B2,:B3,:C1,:C2,:C3] + + @draw = false + @over = false + @player_won = false + @computer_won = false + end + + + def welcome_player() #shows the board and welcomes the player on game start + return current_state,"Welcome #{@player}" + end + + def player=(player_name) + @player = player_name + @current_player = @player if @current_player!="Computer" #If human was current_player, updates after name entered. + end + + def decide_who_goes_first(first_player=nil) + if first_player&&first_player.downcase == :player + @current_player = @player #assign first move to player if specified + elsif first_player&&first_player.downcase == :computer + @current_player = "Computer" #assign first move to computer if specified + else + @current_player = (rand()>0.5) ? @player : "Computer" + end + end + + def randomly_assign_symbols(player_symbol=nil) + if player_symbol + @player_symbol = player_symbol + @computer_symbol = SYMBOLS[SYMBOLS.index(player_symbol)-1] + else + @player_symbol = SYMBOLS[rand.round] #rand.round randomly returns 0 or 1, assigns symbol based on index + @computer_symbol = SYMBOLS[SYMBOLS.index(@player_symbol)-1] #returns the other symbol + end + end + + def indicate_player_turn + print "#{@current_player}'s Move:" + end + + def get_player_move + gets.chomp + end + + def player_move + update_open_spots + move = get_player_move.upcase.to_sym #upcases it (in case entered as lower case) and makes into symbol + validate_move(move) + end + + def validate_move(move) #makes sure a move is valid, and if its not, asks for another one. + if @open_spots.include?(move) + @board[move] = @player_symbol + move + else + print "Error, invalid move. Make another: " + second_try = get_player_move.upcase.to_sym + validate_move(second_try) + end + end + + def computer_move + update_open_spots + #chooses an element from open_spots at random + move = @open_spots.sample + @board[move] = @computer_symbol + puts "Computer's move was #{move.to_s}" + move + end + + def spots_open? + !@open_spots.empty? + end + + def draw? + @draw + end + + def over? + @over + end + + def current_state #makes a heredoc, which when called with puts, prints out the current board configuration + <<-board + =============== + 1 || #{@board[:A1].to_s} | #{@board[:B1].to_s} | #{@board[:C1].to_s} || + 2 || #{@board[:A2].to_s} | #{@board[:B2].to_s} | #{@board[:C2].to_s} || + 3 || #{@board[:A3].to_s} | #{@board[:B3].to_s} | #{@board[:C3].to_s} || + =============== + A B C +board + end + + def determine_winner + update_open_spots + #there are 8 different winning configurations. For both players, check all of them + ["Player","Computer"].each do |player| + symbol = instance_variable_get("@"+player.downcase+"_symbol") #gets the player/computer's symbol + winning_moves = [[@board[:A1],@board[:A2],@board[:A3]], #vertical winning moves + [@board[:B1],@board[:B2],@board[:B3]], + [@board[:C1],@board[:C2],@board[:C3]], + [@board[:A1],@board[:B1],@board[:C1]], #horizontal winning moves + [@board[:A2],@board[:B2],@board[:C2]], + [@board[:A3],@board[:B3],@board[:C3]], + [@board[:A1],@board[:B2],@board[:C3]], #diagonal winning moves + [@board[:A3],@board[:B2],@board[:C1]]] + + winning_moves.each do |move| #for each triplet of winning moves + if move.all?{|spot| spot == symbol} #if each of the spots contains the given player's symbol + @over = true #then the game is over + instance_variable_set("@"+player.downcase+"_won",true) #and that player is the winner + end + end + end + + #if there are no open spots (spots_open? is false) and that game isn't over, then declare the game over and a draw + if spots_open? == false && @over==false + @over = true + @draw = true + end + + next_turn #makes it the next player's turn + end + + def player_won? + @player_won + end + + def computer_won? + @computer_won + end + + private + + def process_optional_arguments(who_goes_first= nil,player_symbol=nil) #deals with optional arguments passed to intialize + + #as far as I can tell, optional arguments to initialize are for testing purposes to get the game into a desired + #configuration. In order to avoid conflicts with certain + + if who_goes_first #if a first player is specified + + if who_goes_first.downcase == :computer #if :computer is going to go first + @player = "Human" + decide_who_goes_first(:computer) #set first player to computer + elsif who_goes_first.downcase == :player #if :player is going to go first + @player = "Human" #gets overridden when player is set to Renee + decide_who_goes_first(:player) + end + #if symbol was passed and its valid + if ( player_symbol && ((player_symbol.upcase ==:X)||(player_symbol.upcase ==:O)) ) + randomly_assign_symbols(player_symbol.upcase) + else + #otherwise, + randomly_assign_symbols + end + + else #if no optional parameters are passed, then randomly assign first mover and symbols. + @player = "Human" + print "Please enter your name: " + self.player = gets.chomp + decide_who_goes_first + randomly_assign_symbols + end + end + + def update_open_spots + made_moves = @board.keys.select{|key| @board[key] != " "} + @open_spots = @open_spots-made_moves + end + + def next_turn + players = [@player,"Computer"] + @current_player = players[players.index(@current_player)-1] + @current_player + end + + +end \ No newline at end of file diff --git a/week7/homework/questions.txt b/week7/homework/questions.txt index d55387d..d62de9d 100644 --- a/week7/homework/questions.txt +++ b/week7/homework/questions.txt @@ -3,7 +3,16 @@ Please Read Chapters 23 and 24 DuckTyping and MetaProgramming Questions: 1. What is method_missing and how can it be used? + => Method_missing is a hook that, after a method is called and not found anywhere in the object class or its ancestors, is activated to raise a method error exception. Since method_missing is essentially a method, it can be modified to suit application-specific needs. + 2. What is and Eigenclass and what is it used for? Where Do Singleton methods live? + => An eigenclass is a special class that contains an object's singleton methods (if any have been defined for it). The eigenclass's parent is the class of which the object in question is an instance. This way, when a method for that object is called, the first place Ruby looks is in that object's eigenclass first. If the method called was a singleton method for that object, then that method will be called, since the eigenclass is where a singleton method lives, and is the first place Ruby looks. If its not a singleton method thats called, Ruby will continue looking in the normal fashion by looking in that object's normal class, then its parent class, and so on, all the way up to BasicObject until the method is found. + 3. When would you use DuckTypeing? How would you use it to improve your code? + => Duck typing would be used in an situation where the behavior of an object is whats important, not necessarily what "sort" of object it is. This allows for more easily-maintainable code that can be adapted over time to implement various objects, so long as they possess the correct behavior (such as the right data structures and methods). + 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 a method called on the class in which the method is defined, whereas instance methods are called on instances of the class for which they are defined. The difference between instance_eval and class_eval is the scope in which the block passed to instance/class_eval is executed. instance_eval acts as if the argument block is passed inside the singleton class of self, whereas class_eval acts as if the argument block is passed inside the class of self. The consequence of this difference is any method defined in instance_eval will be a singleton method available only to self, whereas any defined in class_eval are available to any instance of the class, as if the method were any normal instance method. + 5. What is the difference between a singleton class and a singleton method? + => Singleton class is an alternate name for eigenclass -- the anonymous class in which singleton methods reside when defined on an object --, whereas a singleton method is a method defined on an individual object (rather than its class). Singleton methods live inside singleton classes.