diff --git a/.gitignore b/.gitignore index 18d7cf1..09cdc4a 100644 --- a/.gitignore +++ b/.gitignore @@ -11,11 +11,17 @@ spec/reports test/tmp test/version_tmp tmp +<<<<<<< HEAD *.*~ *~ +======= +>>>>>>> 55106fa09d6f7a2eb0e5e798bd4797a0aec9acb1 # YARD artifacts .yardoc _yardoc doc/ +<<<<<<< HEAD .DS_Store +======= +>>>>>>> 55106fa09d6f7a2eb0e5e798bd4797a0aec9acb1 diff --git a/README.md b/README.md index 4795b4e..0ff9c7b 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,19 @@ +CLASS +HEAD RubyFall2012 ============ Class materials, homework, and solutions for the Fall 2012 Ruby course +<<<<<<< HEAD +======= +Serene Careaga's midterm +======= + +Fall 2012 Ruby Midterm + +There will be three parts: questions, programming problems and a midterm spec. Huzzah. +>>>>>>> 55106fa09d6f7a2eb0e5e798bd4797a0aec9acb1 +======= Syllabus ============ @@ -57,3 +69,4 @@ Week 10 * Final due! * Project due! * Interesting Stuff +>>>>>>> a88274e1eccb1ad82a2f546f2d8b61c3b3a802ff diff --git a/mid_term/questions.txt b/mid_term/questions.txt index 0eba895..82537a2 100644 --- a/mid_term/questions.txt +++ b/mid_term/questions.txt @@ -1,8 +1,12 @@ Instructions for Mid-Term submission and Git Review (10pts): - Create a git repository for your answers + ##done - Add and Commit as you work through the questions and programming problems + ##doing - Your git log should reflect your work, don't just commit after you have finished working + ##done - Use .gitignore to ignore any files that are not relevant to the midterm + ##done - E-mail me your ssh public key - I will email you back with your repository name - Add a remote to your git repository: git@nird.us:RubyFall2012/YOURREPOSITORYNAME.git @@ -11,6 +15,25 @@ Instructions for Mid-Term submission and Git Review (10pts): Questions (20pts): - What are the three uses of the curly brackets {} in Ruby? +<<<<<<< HEAD + ##done + - What is a regular expression and what is a common use for them? + ##done + - What is the difference between how a String, a symbol, a FixNum, and a Float are stored in Ruby? + ##done BUT DOUBLE CHECK + - Are these two statements equivalent? Why or Why Not? + 1. x, y = "hello", "hello" + 2. x = y = "hello" +##done +- What is the difference between a Range and an Array? +##done +- Why would I use a Hash instead of an Array? +##done BUT DOUBLE CHECK +- What is your favorite thing about Ruby so far? +##done +- What is your least favorite thing about Ruby so far? + ##done +======= 1. String interpolation: "#{1+1}" 2. Hash instantiation: {:key => "value"} 3. Block/lambda notation: {puts "hello"} @@ -37,6 +60,7 @@ If I had data which I wanted to reference by meta-data instead of by order I wou - What is your least favorite thing about Ruby so far? nil.object_id => 4 +>>>>>>> ce96056b4f7001234ac8db7a81cbeecd94192f6c Programming Problems (10pts each): - Write a passing rspec file called even_number_spec.rb that tests a class called EvenNumber. diff --git a/mid_term/wish_list_spec.rb b/mid_term/wish_list_spec.rb deleted file mode 100644 index 37beab5..0000000 --- a/mid_term/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 Skyfall"] - 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 Skyfall"] - end - end -end \ No newline at end of file diff --git a/week1/homework/questions.txt b/week1/homework/questions.txt index 0adfd69..bdc9eca 100644 --- a/week1/homework/questions.txt +++ b/week1/homework/questions.txt @@ -1,24 +1,24 @@ +MY COPY FOR REALSIES + Please read: 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. +A thing 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. +Used to keep track of objects; Holds a reference to an object; unique identifiers that bring an object to existence. 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). +An object is an instance of a class; class is like a blueprint and object is the house built from it. 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 sequence of characters contained in quotation marks. 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 +Chomp, new, open 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. +Single quote and double quote. Differences between the two determine degree of substitution. Single-quote strings have more limited functions. Double quotes support more escape sequences (ie. \n). diff --git a/week1/homework/strings_and_rspec_spec.rb b/week1/homework/strings_and_rspec_spec.rb index 2f188f6..3ae87c4 100644 --- a/week1/homework/strings_and_rspec_spec.rb +++ b/week1/homework/strings_and_rspec_spec.rb @@ -1,3 +1,5 @@ +. + # encoding: utf-8 # Please make these examples all pass @@ -11,12 +13,20 @@ context "When a string is defined" do before(:all) do @my_string = "Renée is a fun teacher. Ruby is a really cool programming language" + p @my_string.encoding.name end it "should be able to count the charaters" do +<<<<<<< HEAD @my_string.should have(@my_string.size).characters end it "should be able to split on the . charater" do result = @my_string.split('.') +======= + @my_string.should have(66).characters + end + it "should be able to split on the . charater" do + result = @my_string.split('. ') +>>>>>>> 19191e085c5cd8e019d93533ce03287bce3aa361 result.should have(2).items end it "should be able to give the encoding of the string" do diff --git a/week2/homework/questions.txt b/week2/homework/questions.txt index 4cfc0a3..ea257ec 100644 --- a/week2/homework/questions.txt +++ b/week2/homework/questions.txt @@ -1,8 +1,27 @@ +MINE + Please Read The Chapters on: Containers, Blocks, and Iterators Sharing Functionality: Inheritance, Modules, and Mixins 1. What is the difference between a Hash and an Array? +<<<<<<< HEAD +Arrays use [] operator, hash uses {} (with key value pairs using # =>). Hashes store data in key-value pairs that can use any object as a key. (Arrays store in key-value pairs determined by index position [interger].) + +2. When would you use an Array over a Hash and vice versa? +You would use an array when you simply want data stored in an indexed list. You would use a hash when you need flexibility to pair the value with a key of whatever variety you want to use. + +3. What is a module? Enumerable is a built in Ruby module, what is it? +Modules group together methods, classes and constants. They prevent name clashes and support mixins. Enumberable is a module (a standard mixin?) that implements external iterators; allows iteration over two collections in parallel. + +4. Can you inherit more than one thing in Ruby? How could you get around this problem? +No, restricted to single inheritance from one parent. A work around is to use mixins. + +5. What is the difference between a Module and a Class? +Modules provide methods to multiple classes (functionality focused), cannot be instatiated. Classes create objects, are instantiated, use modules. + + +HERS An array is an ordered list of items that are referenced by their index (order), a hash is a collection of items that can be referenced by a key and have no order. 2. When would you use an Array over a Hash and vice versa? @@ -16,3 +35,4 @@ No, multiple inheritance is not allowed in Ruby. You can include multiple module 5. What is the difference between a Module and a Class? A class can be instantiated into an object, a module cannot. A module is code that can be used across many classes. + diff --git a/week2/homework/simon_says.rb b/week2/homework/simon_says.rb index fa35ccd..09da574 100644 --- a/week2/homework/simon_says.rb +++ b/week2/homework/simon_says.rb @@ -1,4 +1,26 @@ +.. +MINE module SimonSays + + def echo(greeting) + greeting + end + def shout(greeting) + greeting.upcase + end + def repeat(greeting, n=2) + ("#{greeting} " * n).chop + end + def start_of_word(greeting,n) + greeting[0,n] + end + def first_word(greeting) + "#{greeting}".split(' ')[0] + end +end + +HERS + def echo(st) st end @@ -20,3 +42,4 @@ def repeat(st, t=2) ([st]*t).join(' ') end end + diff --git a/week3/homework/calculator.rb b/week3/homework/calculator.rb index f8916e3..6b2fbda 100644 --- a/week3/homework/calculator.rb +++ b/week3/homework/calculator.rb @@ -1,4 +1,7 @@ +HER ANSWERS + class Calculator +<<<<<<< HEAD def sum(array) array.inject(0){|sum, x| sum +x} end @@ -22,3 +25,27 @@ def pow_fac(base=nil, p) (1..p).to_a.inject(1){|f,v| f *= base || v} end end +======= + def sum(n) + ##error expectation + return 0 if n.empty? + n.inject(:+) + end + def mul(n) + n.inject(:*) + end + def power(n) + n.inject(:**) + end + def factorial(n) + return 0 if n==0 + (1..n).inject(:*) + end +end + +stuff = Calculator.new +p stuff.sum([7,11]) +p stuff.mul([8,2,1,5]) +p stuff.power([2,4]) +p stuff.factorial(10) +>>>>>>> f22446d7c1ea0cf75d26c958547a3d11b80f5fd7 diff --git a/week3/homework/calculator_spec.rb b/week3/homework/calculator_spec.rb index 5a418ed..14db030 100644 --- a/week3/homework/calculator_spec.rb +++ b/week3/homework/calculator_spec.rb @@ -26,6 +26,7 @@ # Once the above tests pass, # write tests and code for the following: +<<<<<<< HEAD describe "#multiply" do it "multiplies two numbers" do @calculator.multiply(2,2).should eq 4 @@ -64,5 +65,42 @@ end end +======= + + it "multiplies two numbers" do + @calculator.mul([1,4]).should == 4 + end + + it "multiplies an array of numbers" do + @calculator.mul([8,2,1,5]).should == 80 + end + + it "raises one number to the power of another number" do + @calculator.power([2,4]).should == 16 + end + + # http://en.wikipedia.org/wiki/Factorial + describe "#factorial" do +>>>>>>> f22446d7c1ea0cf75d26c958547a3d11b80f5fd7 + + it "computes the factorial of 0" do + @calculator.factorial(0).should == 0 + end + + it "computes the factorial of 1" do + @calculator.factorial(1).should == 1 + end + it "computes the factorial of 2" do + @calculator.factorial(2).should == 2 + end + it "computes the factorial of 5" do + @calculator.factorial(5).should == 120 + end + it "computes the factorial of 10" do + @calculator.factorial(10).should == 3628800 + end + end end + + diff --git a/week3/homework/questions.txt b/week3/homework/questions.txt index 08067b8..318943d 100644 --- a/week3/homework/questions.txt +++ b/week3/homework/questions.txt @@ -1,10 +1,7 @@ -Please Read: - - Chapter 6 Standard Types - - Review Blocks - - Chapter 7 Regular Expressions - - Chapter 22 The Ruby Language: basic types (symbols), variables and constants + 1. What is a symbol? +<<<<<<< HEAD A symbol is a static name or identifier. 2. What is the difference between a symbol and a string? @@ -15,6 +12,22 @@ A block is an anonymous function, or some code snipt that you can define and the 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: +======= +Symbols are names that start with a colon and are followed by some kind of name. Ex. serene(:awesome) +Also, the use of the symbol guarantees that that wherever it appears in the program, the value will be the same. + +2. What is the difference between a symbol and a string? +A symbol assigns value whereas a string holds data sequences within quote marks. + +3. What is a block and how do I call a block? +A block is a chunk of code applied to methods (like parameters) and are called between braces or between do..end. + +4. How do I pass a block to a method? What is the method signature? +A block is passed into a method by placing the code in braces after the parameters. The method can call the block within it's parameters by using the yield method. + +5. Where would you use regular expressions? +When there is a pattern that needs to be matched up against a string. +>>>>>>> f22446d7c1ea0cf75d26c958547a3d11b80f5fd7 my_array.each {|a| puts a} diff --git a/week4/homework/questions.txt b/week4/homework/questions.txt index bc1ab7c..cbb8197 100644 --- a/week4/homework/questions.txt +++ b/week4/homework/questions.txt @@ -3,7 +3,23 @@ Chapter 10 Basic Input and Output The Rake Gem: http://rake.rubyforge.org/ 1. How does Ruby read files? +The method gets reads a line from standard input (or from files specified on command line when script invoked) and file.gets reads the line from the file object file. + 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? + +Objects from the class represent directories in the underlying file system and can list directories and contents. Ex: mkdir (creates director), chider (changes directory), .exist? (checks path and returns true if it exists) + 4. What is an IO object? + +A bidirectional channel between a Ruby program and an external source. + + 5. What is rake and what is it used for? What is a rake task? +A build tool that is used in Rails and resembles Ruby's makefile. (Wikipedia calls it a software management tool.) +A rake task is a set of procedures that are often have dependencies or can have prerequisites that depend on another task. They can also be automated with cron jobs. \ No newline at end of file diff --git a/week7/class_materials/minitest/book.rb b/week7/class_materials/minitest/book.rb index 294444b..c0bd5d2 100644 --- a/week7/class_materials/minitest/book.rb +++ b/week7/class_materials/minitest/book.rb @@ -1,9 +1,17 @@ +<<<<<<< HEAD +#helps test run +======= class Book end +>>>>>>> 7a51db287e3acee6bc9678f2d9531ecd3e8bc7c4 require 'minitest/autorun' # Unit tests +#class Book +# def initialize +# end +#end class TestBook < MiniTest::Unit::TestCase def setup diff --git a/week7/exercises/features/puppy.feature b/week7/exercises/features/puppy.feature deleted file mode 100644 index e6c7b07..0000000 --- a/week7/exercises/features/puppy.feature +++ /dev/null @@ -1,18 +0,0 @@ -Feature: Puppies are very cute and everyone wants one - In order to make everyone happy - As a puppy class programmer - I want to give everyone a cute virtual puppy - -Scenario: The puppy is being pet - Given we have a puppy - And its name is Fred - When we pet the puppy - Then the puppy wags its tail - -Scenario: The puppy needs to go out - Given we have a puppy - And its name is Bella - When we ring the bell - And it wags its tail - Then we must take it out - And then it will not pee on the floor diff --git a/week7/exercises/features/step_definitions/converter.rb b/week7/exercises/features/step_definitions/converter.rb index 4cb1264..3ec3968 100644 --- a/week7/exercises/features/step_definitions/converter.rb +++ b/week7/exercises/features/step_definitions/converter.rb @@ -1,6 +1,12 @@ class Converter +<<<<<<< HEAD + + def initialize(unit) + @unit = unit.to_f +======= def initialize(value) @value = value.to_f +>>>>>>> 7a51db287e3acee6bc9678f2d9531ecd3e8bc7c4 end def type=(type) @@ -8,10 +14,24 @@ def type=(type) end def convert +<<<<<<< HEAD + self.send("#{@type}_conversion") + end + + def Celsius_conversion + (@unit * (9.0/5.0) + 32.0).round(1) + end + + def Fahrenheit_conversion + (@unit - 32.0 * (5.0/9.0)).round(1) + end +end +======= self.send("#{@type}_convertion") end def Fahrenheit_convertion (((@value - 32.0) /5.0) * 9.0).round(1) end -end \ No newline at end of file +end +>>>>>>> 7a51db287e3acee6bc9678f2d9531ecd3e8bc7c4 diff --git a/week7/exercises/features/step_definitions/converter_steps.rb b/week7/exercises/features/step_definitions/converter_steps.rb index 5a12ae5..821af88 100644 --- a/week7/exercises/features/step_definitions/converter_steps.rb +++ b/week7/exercises/features/step_definitions/converter_steps.rb @@ -6,10 +6,19 @@ @converter.type = arg1 end +<<<<<<< HEAD + +======= +>>>>>>> 7a51db287e3acee6bc9678f2d9531ecd3e8bc7c4 When /^I press (\w+)$/ do |arg1| @result = @converter.send(arg1) end +<<<<<<< HEAD + +Then /^the result should be (\d+)\.(\d+) on the screen$/ do |arg1, arg2| +======= Then /^the result returned should be (\d+)\.(\d+)$/ do |arg1, arg2| +>>>>>>> 7a51db287e3acee6bc9678f2d9531ecd3e8bc7c4 @result.should == "#{arg1}.#{arg2}".to_f end \ No newline at end of file diff --git a/week7/homework/features/step_definitions/pirate.rb b/week7/homework/features/step_definitions/pirate.rb index d2a6f6a..7ceccf3 100644 --- a/week7/homework/features/step_definitions/pirate.rb +++ b/week7/homework/features/step_definitions/pirate.rb @@ -1,17 +1,35 @@ class PirateTranslator - PIRATE_WORDS = { - "Hello Friend" => "Ahoy Matey" - } - def say(str) - @said = lookup_pirate(str).to_s + + +attr_accessor :talk + + def initialize(talk) + @talk = talk end - def translate - @said + "\n Shiber Me Timbers You Scurvey Dogs!!" + def talk + @talk end -private - def lookup_pirate(str) - PIRATE_WORDS[str] + def translate(talk) + @translate = "Ahoy Matey" && "Shiber Me Timbers You Scurvey Dogs!!" + puts "#{@translate}" end -end \ No newline at end of file +end + +#Renee's +# PIRATE_WORDS = { +# "Hello Friend" => "Ahoy Matey" +# } +# def say(str) +# @said = lookup_pirate(str).to_s +# end + +# def translate +# @said + "\n Shiber Me Timbers You Scurvey Dogs!!" +# end + +#private +# def lookup_pirate(str) +# PIRATE_WORDS[str] +# end diff --git a/week7/homework/features/step_definitions/pirate_steps.rb b/week7/homework/features/step_definitions/pirate_steps.rb index faf1a7f..2bb7f0e 100644 --- a/week7/homework/features/step_definitions/pirate_steps.rb +++ b/week7/homework/features/step_definitions/pirate_steps.rb @@ -1,19 +1,41 @@ -Gangway /^I have a (\w+)$/ do |arg| - @translator = Kernel.const_get(arg).new + +Gangway /^I have a PirateTranslator$/ do + @t = PirateTranslator.new('Hello Friend') end -Blimey /^I (\w+) '(.+)'$/ do |method, arg| - @translator.send(method, arg) +Blimey /^I say 'Hello Friend'$/ do + @talk end -Letgoandhaul /^I hit (\w+)$/ do |arg| - @result = @translator.send(arg) +Blimey /^I hit translate$/ do + @translate end -Letgoandhaul /^it prints out '(.+)'$/ do |arg| - @result.split("\n ").first.should == arg +Letgoandhaul /^it prints out 'Ahoy Matey'$/ do + @translate = "Ahoy Matey" end -Letgoandhaul /^it also prints '(.+)'$/ do |arg| - @result.split("\n ").last.should == arg +Letgoandhaul /^it also prints 'Shiber Me Timbers You Scurvey Dogs!!'$/ do + @translate = "Shiber Me Timbers You Scurvey Dogs!!" + + +#renee's +#Gangway /^I have a (\w+)$/ do |arg| +# @translator = Kernel.const_get(arg).new +#end + +#Blimey /^I (\w+) '(.+)'$/ do |method, arg| +# @translator.send(method, arg) +#end + +#Letgoandhaul /^I hit (\w+)$/ do |arg| +# @result = @translator.send(arg) +#end + +#Letgoandhaul /^it prints out '(.+)'$/ do |arg| +# @result.split("\n ").first.should == arg end + +#Letgoandhaul /^it also prints '(.+)'$/ do |arg| +# @result.split("\n ").last.should == arg +#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 b353120..68f7d6b 100644 --- a/week7/homework/features/step_definitions/tic-tac-toe-steps.rb +++ b/week7/homework/features/step_definitions/tic-tac-toe-steps.rb @@ -1,11 +1,13 @@ + require 'rspec/mocks/standalone' +#require 'rspec/exceptions' 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 +When /^I enter my name (\w+)$/ do |arg1| + @game.player = arg1 end Then /^the computer welcomes me to the game with "(.*?)"$/ do |arg1| @@ -13,7 +15,7 @@ end Then /^randomly chooses who goes first$/ do - [@game.player, "Computer"].should include @game.current_player + [@game.player, :computer].should include @game.current_player end Then /^who is X and who is O$/ do @@ -35,7 +37,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/tic-tac-toe.rb b/week7/homework/features/step_definitions/tic-tac-toe.rb new file mode 100644 index 0000000..129bbf0 --- /dev/null +++ b/week7/homework/features/step_definitions/tic-tac-toe.rb @@ -0,0 +1,183 @@ +class TicTacToe + SYMBOLS = [:X, :O] + attr_accessor :player, :board, :player_symbol, :computer_symbol, :current_player, :next_player, :over, :taken_spot, :player_move, :open_spot, :winning_move + + + def initialize(first_player=nil,player_symbol=nil) + @board = { + A1: " ", A2: " ", A3: " ", + B1: " ", B2: " ", B3: " ", + C1: " ", C2: " ", C3: " " + } + if first_player.nil? + random_start + else + set_first_player(first_player) + end + if player_symbol.nil? + random_symbol + else + @player_symbol = player_symbol + @computer_symbol = (SYMBOLS - [@player_symbol])[0] + end + @winning_move = {:A => [:A1,:A2,:A3], :B => [:B1,:B2,:B3], :C => [:C1,:C2,:C3], + :D => [:A1,:B1,:C1], :E =>[:A2,:B2,:C2], :F => [:A3,:B3,:C3], :G=>[:C1, :B2, :A3], + :H=>[:A1,:B2,:C3]} + end + + + def welcome_player + "Welcome #{@player}" + end + + def set_first_player(p) + @current_player = p + end + + def random_start + if rand(0..1).zero? + set_first_player(:player) + else + set_first_player(:computer) + end + end + + def random_symbol + if rand(0..1).zero? + @player_symbol = SYMBOLS[0] + @computer_symbol = SYMBOLS[1] + else + @player_symbol = SYMBOLS[1] + @computer_symbol = SYMBOLS[0] + end + end + + def current_player + if @current_player == :computer + "Computer" + elsif @player != nil + @player + else + "Player" + end + end + + def next_turn + @current_player = :computer if @current_player == :player + @current_player = :player if current_player == :computer + end + + + def set_symbol(p,s) + end + + def indicate_player_turn + if current_player == :computer + "Computer's Move:" + else player != nil + "#{@player}'s Move:" + end + end + + def get_player_move + move = gets.chomp + @board[move] = @player_symbol + end + + def open_spots + @board.select{ |k,v| v == " " } + end + + def computer_move + computer_square = open_spots.keys.sample + @board[computer_square] = @computer_symbol.to_s + computer_square + end + + def player_move + player_move = get_player_move.to_sym + open_spots + #player_square = player_move + #@board[player_square] = @player_symbol + #player_square + if (open_spots.include?(player_move)) + @board[player_move] = player_symbol.to_s + else + player_move = get_player_move.to_sym + end + player_move + end + + def old_pos + #@old_pos = @board[player_move] + + #get_player_move + + #player_square = open_spots.has_value?(" ") + + #case + # when false + # puts "Try again, dummy." + # else true + # player_move = @board[player_symbol] + # end + + #end + #player_square = open_spots.get_player_move.to_sym + + #@board[player_square] = @player_symbol + #player_move = @board[player_square] + + end + + def spots_open? + #true unless open_spots.value != " " + end + + def indicate_player_move + puts "#{@player}'s Move:" + end + + def current_state + @board.values + end + + def determine_winner + player_plays = @board.reject{|k,v| v != @player_symbol}.keys + computer_plays = @board.reject{|k,v| v != @computer_symbol}.keys + @winning_move.each_value{|v| + if v.include?(player_plays) + player_won? + elsif v.include?(computer_plays) + computer_won? + else + draw? + end + } + end + + def computer_won? + true + over? + end + + def player_won? + true + over? + end + + def spots_open? + open_spots + !(open_spots.empty?) + end + + def over? + true + end + + def draw? + true + end + + +end \ No newline at end of file diff --git a/week7/homework/features/tic-tac-toe.feature b/week7/homework/features/tic-tac-toe.feature index 6f3134d..f73d08c 100644 --- a/week7/homework/features/tic-tac-toe.feature +++ b/week7/homework/features/tic-tac-toe.feature @@ -1,3 +1,4 @@ + Feature: Tic-Tac-Toe Game As a game player I like tic-tac-toe In order to up my skills diff --git a/week7/homework/questions.txt b/week7/homework/questions.txt index d55387d..916d13d 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? -2. What is and Eigenclass and what is it used for? Where Do Singleton methods live? +It is a method that is called when there is no explicit receiver (ie. items.size) and no method defined. The missing_method will move up the superclass chain to find the method definition until it's been exhausted. + +2. What is and Eigenclass and what is it used for? Where Do Singleton methods live? Eigenclass is the anonymous class Ruby creates wihen a singleton method is written. Singleton methods live in an anonymous class, also referred to as a singleton class or eigenclass. + 3. When would you use DuckTypeing? How would you use it to improve your code? +Duck Typing can be used whenever you feel comfortable with having flexibility. It's just a style of programming that isn't as explicit or rigid as others. It can be really helpful in simplifying code (in that you aren't using extra lines to define arguments or types that you don't necessarily need to) and being responsive to tests. + 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 available to within the class itself, whereas an instance method is available to an object being instantiated by the class. + + 5. What is the difference between a singleton class and a singleton method? +A singleton method is a method defined to one specific object. A singleton class is generated by Ruby to contain singleton methods (aka eigenclass). \ No newline at end of file diff --git a/week8/class_materials/couch.rb b/week8/class_materials/couch.rb index 41d0097..1af35a3 100644 --- a/week8/class_materials/couch.rb +++ b/week8/class_materials/couch.rb @@ -12,9 +12,14 @@ def how_many_cushions @cushions.count end - [:pillows, :cushions].each do |s| +#metaprogramming section + [:pillows, :cushions].each do |s| #string define_method("how_many_#{s}") do instance_variable_get("@#{s}").count + #remember the symbol! end end end + + + diff --git a/week8/exercises/books.rb b/week8/exercises/books.rb index bb843b3..7a48ca9 100644 --- a/week8/exercises/books.rb +++ b/week8/exercises/books.rb @@ -1,13 +1,20 @@ class Printer def print(book) - "This book is a book" - "This book is Fiction!" if book.is_a?(FictionBook) + "This book is a #{book.type}" end end class Book attr_accessor :title, :author + def print + "This is a book" + end end class FictionBook < Book + def print + "This book is Fiction!" + end end + +##wouldn't be class that is printing out. each type of book should know it's own printing value \ No newline at end of file diff --git a/week8/exercises/couch.rb b/week8/exercises/couch.rb index a52eb35..8374507 100644 --- a/week8/exercises/couch.rb +++ b/week8/exercises/couch.rb @@ -4,17 +4,37 @@ def initialize(pillows, cushions) @cushions = cushions end - def pillow_colors - @pillows.join(", ") +#custom method_missing + def method_missing(meth,*args, &block) + puts “You called #{meth} with #{args.join(‘ ‘)}” + puts "#{self}" + self.class.class_eval do + define_method(meth) do + puts "hi" + end end - def cushion_colors - @cushions.join(", ") + self.send(meth) + + def to_str + "Hi, I'm a couch" + end + + def respond_to?(meth) + true end +#count method [:pillows, :cushions].each do |s| define_method("how_many_#{s}") do instance_variable_get("@#{s}").count end +#colors method + define_method("#{s}_colors") do + instance_variable_get("@#{s}").join(' ') + end end end + +c=Couch.new["purple","pink","green"] +