diff --git a/week1/homework/questions.txt b/week1/homework/questions.txt index 2257bb9..9950e24 100644 --- a/week1/homework/questions.txt +++ b/week1/homework/questions.txt @@ -3,13 +3,21 @@ Chapter 3 Classes, Objects, and Variables p.86-90 Strings (Strings section in Chapter 6 Standard Types) 1. What is an object? +An object is structure of memory with associated methods that act on the members of the structure. 2. What is a variable? +A variable is a symbolic reference to an object 3. What is the difference between an object and a class? +A class is a definition of an object, an object is a specific instance of a class 4. What is a String? +A string is a sequence of characters 5. What are three messages that I can send to a string object? Hint: think methods +squeeze, split, chomp 6. What are two ways of defining a String literal? Bonus: What is the difference between them? +strings are delimited by special characters at the beginning and end of the string. Ruby has several forms of delimeters: single quotes, double quotes, %{} where { and } may be any pair of braces ({,[,etc). There are also here documents which begin < 0 + end it "should be able to split on the . charater" do - pending - result = #do something with @my_string here + result = @my_string.split('.') result.should have(2).items 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 + @my_string.encoding.should eq (Encoding.find("UTF-8")) end end end diff --git a/week2/homework/questions.txt b/week2/homework/questions.txt index 939e42d..727c0ce 100644 --- a/week2/homework/questions.txt +++ b/week2/homework/questions.txt @@ -3,11 +3,18 @@ Containers, Blocks, and Iterators Sharing Functionality: Inheritance, Modules, and Mixins 1. What is the difference between a Hash and an Array? +A hash is a collection of key-value pairs that can be accessed by unique keys. An array is a collection that is accessed by numeric index. 2. When would you use an Array over a Hash and vice versa? +An array can access its elements instanenously by its index. If a particular object needs to be access by a key value, for example by name, then a Hash collection who's key is a name string would be ideal. Arrays are useful as stacks or queues. Hash's are useful when you need rapid access by arbitrary keys. 3. What is a module? Enumerable is a built in Ruby module, what is it? +A module is a way to provide a namespace for a group of methods, classes, and constants. As a namspace, a module helps prevent collisions with other unrelated but similary named methods, classes, and constants. A module also lets you mixin module methods into classes. + +The Enumerable module defines methods that iterate over collections, such as map, include?, find_all?. One can define their own collection class by defining an iterator method called 'each' which returns elements in the collection. That class may include or 'mixin' the Enumerator module and the new collection class now has all the standard Enumerable methods. 4. Can you inherit more than one thing in Ruby? How could you get around this problem? + No, a class can only inherit from a single base class. You can, however, mixin as many modules as you want within a class. 5. What is the difference between a Module and a Class? + A module just defines a namespace and grouping of a set of methods, classes, and constants. A class defines a type of object. A class can be instaniated into an object, modules cannot. Classes can inherit from other classes, modules cannot. A module can be included in classes and other modules. \ No newline at end of file diff --git a/week2/homework/simon_says.rb b/week2/homework/simon_says.rb new file mode 100644 index 0000000..29f3305 --- /dev/null +++ b/week2/homework/simon_says.rb @@ -0,0 +1,23 @@ +module SimonSays + + def echo(word) + word + end + + def shout(word) + word.upcase + end + + def repeat(word, count = 2) + ((word + " ") * count).rstrip + end + + def start_of_word(word, count) + word[0, count] + end + + def first_word(sentence) + sentence.split(" ").first + end + +end \ No newline at end of file diff --git a/week3/homework/calculator.rb b/week3/homework/calculator.rb new file mode 100644 index 0000000..9fdb30a --- /dev/null +++ b/week3/homework/calculator.rb @@ -0,0 +1,65 @@ +class Calculator + + def pow power, number + p = 1 + number.times { p *= power } + p + end + + def sum array + s = 0 + array.each do |value| + s += value + end + s + end + + def multiply *args + if args[0].class == Array + multiplyArray args[0] + else + multiplyArray args + end + end + + def multiplyArray array + m = 1 + array.each do |value| + m *= value + end + m + end + + def multiply_Alternative *args + if args[0].class == Array + array = args[0] + else + array = args + end + m = 1 + array.each do |value| + m *= value + end + m + end + + def multiply_Alternative2 numOrArray, num = 0 + m = 1 + if numOrArray.class == Array + numOrArray.each do |value| + m *= value + end + else + m = numOrArray * num + end + m + end + + def fac n + f = 1 + (1..n).each do |a| + f *= a + end + f + end +end diff --git a/week3/homework/questions.txt b/week3/homework/questions.txt index dfb158d..77c33c3 100644 --- a/week3/homework/questions.txt +++ b/week3/homework/questions.txt @@ -5,11 +5,20 @@ Please Read: - Chapter 22 The Ruby Language: basic types (symbols), variables and constants 1. What is a symbol? + A symbol is an identifier that is a string of characters. A particular name or string will always generate the same symbol, so they are useful as unique keys in code. 2. What is the difference between a symbol and a string? + A symbol is used as an indentifier in code, a string is a variable to hold user data, results, etc. 3. What is a block and how do I call a block? + A block is a segment of executable code, like any function but it doesn't have a name -- its an anonymous function. A block can be assigned to a variable or passed to a function as a parameter. Blocks can be called using the 'call' method on a Proc object. 4. How do I pass a block to a method? What is the method signature? + A block can be passed to a method using a variable in any argument, or the if the last parameter is declard with an &, then an inline block can appear immediately after the function calls other regular parameters (if any). For example: + def foo &block + end + ... + foo do ... end 5. Where would you use regular expressions? + A regular expression can be used to test to see if a particular pattern exists in a string. It can also be used to extract pattern matches from strings or perform substitutions in strings. diff --git a/week4/homework/questions.txt b/week4/homework/questions.txt index ffaf215..5298152 100644 --- a/week4/homework/questions.txt +++ b/week4/homework/questions.txt @@ -3,11 +3,19 @@ Chapter 10 Basic Input and Output The Rake Gem: http://rake.rubyforge.org/ 1. How does Ruby read files? + Ruby reads files similar to how it can get steams from the console. + If a filename was passed to ruby after the ruby script itself, then the Kernel 'gets' will lines from the file instead of the console. A File object can also be created with a file path (File.new("filename", "r")) and then #gets can be called on the file object to get lines of text, or #read to read an arbitrary number of bytes from the file. 2. How would you output "Hello World!" to a file called my_output.txt? + f = File.new("my_output.txt", "w") + f.puts("Hello World!") + f.close 3. What is the Directory class and what is it used for? + The Dir class lets ruby inspect directories in the underlying file system. For example Dir.entries("/") returns an array containing all the filename of the files in the root directory of the system. 4. What is an IO object? + The IO class is the basis for input and output in ruby. It is the base class of File and the socket classes like TCPSocket and UDPSocket. It defines the methods such as #gets, #puts, #read and #print that read or write steams of characters. 5. What is rake and what is it used for? What is a rake task? + Rake is a make file like build program. Rakefiles let you define build tasks and describe dependencies between files. Rakefiles are a domain specific language in ruby syntax. a rake task is a block of ruby code that rake runs when a rule or dependency triggers it to be run. \ No newline at end of file diff --git a/week4/homework/worker.rb b/week4/homework/worker.rb new file mode 100644 index 0000000..97d0d09 --- /dev/null +++ b/week4/homework/worker.rb @@ -0,0 +1,11 @@ +module Worker + + def self.work t = 1 + result = nil + t.times do + result = yield + end + result + end + +end \ No newline at end of file diff --git a/week5/exercises/rakefile.rb b/week5/exercises/rakefile.rb new file mode 100644 index 0000000..079aa00 --- /dev/null +++ b/week5/exercises/rakefile.rb @@ -0,0 +1,24 @@ + +task :name_students do + f = File.new "names" + + f.each do |name| + puts name + end +end + +task :create_class_dir do + Dir.mkdir("class") +end + +task :create_student_dirs => [:create_class_dir] do + f = File.new "names" + + Dir.chdir("class") + + f.each do |name| + Dir.mkdir name.chop + end + + Dir.chdir("..") +end \ No newline at end of file diff --git a/week6/homework/tomun_test_gem/.rspec b/week6/homework/tomun_test_gem/.rspec new file mode 100644 index 0000000..b782d24 --- /dev/null +++ b/week6/homework/tomun_test_gem/.rspec @@ -0,0 +1 @@ +--color --format documentation \ No newline at end of file diff --git a/week6/homework/tomun_test_gem/RakeFile b/week6/homework/tomun_test_gem/RakeFile new file mode 100644 index 0000000..41d198d --- /dev/null +++ b/week6/homework/tomun_test_gem/RakeFile @@ -0,0 +1,5 @@ +require 'rspec/core/rake_task' + +RSpec::Core::RakeTask.new('spec') + +task :default => :spec \ No newline at end of file diff --git a/week6/homework/tomun_test_gem/bin/tomun_test_gem b/week6/homework/tomun_test_gem/bin/tomun_test_gem new file mode 100755 index 0000000..65d512d --- /dev/null +++ b/week6/homework/tomun_test_gem/bin/tomun_test_gem @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby + +require_relative "../lib/tomun_test_gem.rb" + +run diff --git a/week6/homework/tomun_test_gem/lib/tomun_test_gem.rb b/week6/homework/tomun_test_gem/lib/tomun_test_gem.rb new file mode 100644 index 0000000..5a28d57 --- /dev/null +++ b/week6/homework/tomun_test_gem/lib/tomun_test_gem.rb @@ -0,0 +1,3 @@ +def run + puts "Tomun's test gem" +end \ No newline at end of file diff --git a/week6/homework/tomun_test_gem/spec/tomun_test_gem_spec.rb b/week6/homework/tomun_test_gem/spec/tomun_test_gem_spec.rb new file mode 100644 index 0000000..6edee0c --- /dev/null +++ b/week6/homework/tomun_test_gem/spec/tomun_test_gem_spec.rb @@ -0,0 +1,8 @@ +require_relative '../lib/tomun_test_gem' + +describe "Test Gem" do + + it "Runs" do + expect { run }.to output("Tomun's test gem\n").to_stdout + end +end diff --git a/week6/homework/tomun_test_gem/tomun_test_gem-1.0.0.gem b/week6/homework/tomun_test_gem/tomun_test_gem-1.0.0.gem new file mode 100644 index 0000000..9234f8b Binary files /dev/null and b/week6/homework/tomun_test_gem/tomun_test_gem-1.0.0.gem differ diff --git a/week6/homework/tomun_test_gem/tomun_test_gem.gemspec b/week6/homework/tomun_test_gem/tomun_test_gem.gemspec new file mode 100644 index 0000000..8d5ae2a --- /dev/null +++ b/week6/homework/tomun_test_gem/tomun_test_gem.gemspec @@ -0,0 +1,13 @@ +Gem::Specification.new do |s| + s.name = 'tomun_test_gem' + s.version = '1.0.0' + s.date = '2014-11-07' + s.summary = "Tomun's Test Gem" + s.description = "A gem to for Week 6 homework" + s.authors = ["Tom Underhill"] + s.email = 'tunderhill@gmail.com' + s.homepage = 'http://www.tomunderhill.cu.cc' + s.licenses = ['MIT'] + s.files = ["lib/tomun_test_gem.rb"] + s.executables = ["tomun_test_gem"] +end \ No newline at end of file diff --git a/week7/exercises/features/step_definitions/converter.rb b/week7/exercises/features/step_definitions/converter.rb new file mode 100644 index 0000000..55eab40 --- /dev/null +++ b/week7/exercises/features/step_definitions/converter.rb @@ -0,0 +1,19 @@ +class Converter + attr_accessor :value + attr_accessor :type + + def initialize + end + + def convert + # [°C] = ([°F] - 32) × 5/9 + # [°F] = [°C] × 9/5 + 32 + + if type == :fahrenheit + value * 9/5 + 32 + else + (value - 32) * 5/9 + end + end + +end \ No newline at end of file diff --git a/week7/exercises/features/step_definitions/converter_steps.rb b/week7/exercises/features/step_definitions/converter_steps.rb new file mode 100644 index 0000000..c54bfef --- /dev/null +++ b/week7/exercises/features/step_definitions/converter_steps.rb @@ -0,0 +1,17 @@ + +Given(/^I have entered (\d+) into the converter$/) do |arg1| + @converter = Converter.new + @converter.value = arg1.to_f +end + +Given(/^I set the type to Fahrenheit$/) do + @converter.type = :fahrenheit +end + +When(/^I press convert$/) do + @result = @converter.convert +end + +Then(/^the result returned should be (\d+)\.(\d+)$/) do |arg1, arg2| + @converter.value == "#{arg1}.#{arg2}" +end diff --git a/week7/homework/features/step_definitions/pirate_translator.rb b/week7/homework/features/step_definitions/pirate_translator.rb new file mode 100644 index 0000000..89a9cb2 --- /dev/null +++ b/week7/homework/features/step_definitions/pirate_translator.rb @@ -0,0 +1,12 @@ +class PirateTranslator + def say string + @message = string + end + + def translate + pirate = @message + pirate.gsub!("Hello", "Ahoy"); + pirate.gsub!("Friend", "Matey"); + pirate << "\n Shiber Me Timbers You Scurvey Dogs!!" + end +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..319357e 100644 --- a/week7/homework/features/step_definitions/tic-tac-toe-steps.rb +++ b/week7/homework/features/step_definitions/tic-tac-toe-steps.rb @@ -1,5 +1,6 @@ require 'rspec/mocks/standalone' require 'rspec/expectations' + Given /^I start a new Tic\-Tac\-Toe game$/ do @game = TicTacToe.new end @@ -34,16 +35,16 @@ end Then /^the computer prints "(.*?)"$/ do |arg1| - @game.should_receive(:puts).with(arg1) + expect(@game).to receive(:puts).with(arg1) @game.indicate_palyer_turn end Then /^waits for my input of "(.*?)"$/ do |arg1| - @game.should_receive(:gets).and_return(arg1) + expect(@game).to receive(:gets).and_return(arg1) @game.get_player_move end -Given /^it is the computer's turn$/ do +Given /^it is the computer\x27s turn$/ do @game = TicTacToe.new(:computer, :O) @game.current_player.should eq "Computer" end @@ -69,7 +70,9 @@ When /^I enter a position "(.*?)" on the board$/ do |arg1| @old_pos = @game.board[arg1.to_sym] - @game.should_receive(:get_player_move).and_return(arg1) + expect(@game).to receive(:gets).and_return(arg1) #added + @game.get_player_move #added + expect(@game).to receive(:get_player_move).and_return(arg1) @game.player_move.should eq arg1.to_sym end @@ -77,22 +80,22 @@ @old_pos.should eq " " end -Then /^it is now the computer's turn$/ do +Then /^it is now the computer\x27s turn$/ do @game.current_player.should eq "Computer" end -When /^there are three X's in a row$/ do +When /^there are three X\x27s 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 - @game.player_won?.should be_true + @game.player_won?.should be_truthy end Then /^the game ends$/ do - @game.over?.should be_true + @game.over?.should be_truthy end Given /^there are not three symbols in a row$/ do @@ -105,11 +108,11 @@ end When /^there are no open spaces left on the board$/ do - @game.spots_open?.should be_false + @game.spots_open?.should be_falsey end Then /^the game is declared a draw$/ do - @game.draw?.should be_true + @game.draw?.should be_truthy end When /^"(.*?)" is taken$/ do |arg1| @@ -119,6 +122,15 @@ Then /^computer should ask me for another position "(.*?)"$/ do |arg1| @game.board[arg1.to_sym] = ' ' - @game.should_receive(:get_player_move).twice.and_return(@taken_spot, arg1) + #expect(@game).to receive(:get_player_move).twice.and_return(@taken_spot, arg1) + + expect(@game).to receive(:gets).and_return(@taken_spot) #added + @game.get_player_move #added + expect(@game).to receive(:get_player_move).and_return(@taken_spot) #added + + expect(@game).to receive(:gets).and_return(arg1) #added + @game.get_player_move #added + expect(@game).to receive(:get_player_move).and_return(arg1) #added + @game.player_move.should eq arg1.to_sym end diff --git a/week7/homework/features/step_definitions/tic-tac-toe.rb b/week7/homework/features/step_definitions/tic-tac-toe.rb new file mode 100644 index 0000000..f2fd32c --- /dev/null +++ b/week7/homework/features/step_definitions/tic-tac-toe.rb @@ -0,0 +1,199 @@ +class TicTacToe + + attr_accessor :player + attr_reader :player_symbol + attr_reader :computer_symbol + attr_accessor :board + + SYMBOLS = [ :X, :O ] + + def initialize who_starts = nil, other_players_symbol = :X + if who_starts == nil + if Random.new.rand(0..1) == 1 + @turn = :player + else + @turn = :computer + end + else + @turn = who_starts + end + if @turn == :player + @computer_symbol = other_players_symbol + @player_symbol = opposite_symbol_of other_players_symbol + else + @player_symbol = other_players_symbol + @computer_symbol = opposite_symbol_of other_players_symbol + end + + @board = {} + for x in 0..2 + for y in 0..2 + coords = coords_to_sym x, y + @board[coords] = " " + end + end + end + + def opposite_symbol_of symbol + i = SYMBOLS.index symbol + if i != nil + SYMBOLS[1 - i] + end + end + + def welcome_player + "Welcome #{player}" + end + + def current_player + if @turn == :player + @player + else + "Computer" + end + end + + def indicate_palyer_turn + print "#{current_player}'s Move:" + end + + def get_player_move + move = nil + loop do + move = gets.chomp.to_sym + break if @board.has_key?(move) && @board[move] == " " + print "Invalid move, try again:" + end + @board[move] = @player_symbol + @turn = :computer + move + end + + def player_move + move = self.get_player_move + move.to_sym + end + + def computer_move + begin + x = Random.new.rand(0..2) + y = Random.new.rand(0..2) + coords = coords_to_sym x, y + end while @board[coords] != " " + @board[coords] = @computer_symbol + @turn = :player + coords + end + + def coords_to_sym x, y + "#{('A'..'C').to_a[y]}#{x+1}".to_sym + end + + def open_spots + open = [] + for x in 0..2 + for y in 0..2 + coords = coords_to_sym x, y + if @board[coords] == " " + open << coords + end + end + end + open + end + + def spots_open? + open_spots.length > 0 + end + + def current_state + state = " 1 2 3\n" + for y in 0..2 + state << "#{('A'..'C').to_a[y]} " + for x in 0..2 + coords = coords_to_sym x, y + state << @board[coords].to_s + if x < 2 + state << '|' + end + end + state << "\n" + if y < 2 + state << " -+-+-\n" + end + end + state << "\n" + end + + def determine_winner + @winner = nil + + # horizontal + for y in 0..2 + row = "" + for x in 0..2 + row << @board[coords_to_sym(x, y)].to_s + end + determine_if_winner row + end + + # vertical + for x in 0..2 + row = "" + for y in 0..2 + row << @board[coords_to_sym(x, y)].to_s + end + determine_if_winner row + end + + # diagonal left-top to bottom + row = "" + for i in 0..2 + row << @board[coords_to_sym(i, i)].to_s + end + determine_if_winner row + + # diagonal right-top to bottom + row = "" + for i in 0..2 + row << @board[coords_to_sym(2 - i, i)].to_s + end + determine_if_winner row + + if @winner == nil && !spots_open? + @winner = :draw + end + end + + def determine_if_winner row + if row == "XXX" + if @player_symbol == :X + @winner = :player + else + @winner = :computer + end + elsif row == "OOO" + if @player_symbol == :O + @winner = :player + else + @winner = :computer + end + end + end + + def player_won? + @winner == :player + end + + def computer_won? + @winner == :computer + end + + def over? + @winner != nil + end + + def draw? + @winner == :draw + end +end \ No newline at end of file diff --git a/week7/homework/questions.txt b/week7/homework/questions.txt index d55387d..2014e26 100644 --- a/week7/homework/questions.txt +++ b/week7/homework/questions.txt @@ -3,7 +3,21 @@ Please Read Chapters 23 and 24 DuckTyping and MetaProgramming Questions: 1. What is method_missing and how can it be used? + method_missing is called when Ruby could not find the method on the objects class nor any of its base classes. One use of overriding method_missing is to simulate an accessor method on an object. An object that normally doesn't have a setter could be given a setter by hooking into method_missing and handling foo=. + 2. What is and Eigenclass and what is it used for? Where Do Singleton methods live? + When a singleton method is defined it needs its own own anonymous class created behind theh scenes. These Eigenclass, or metaclasses is where the singleton method gets added. + 3. When would you use DuckTypeing? How would you use it to improve your code? + You could use duck typing in a module where you don't want a type to be coupled tightly with, or indeed know anything about the specific classes that may be including your module. This can make your modules highly reusable and help you "not repeat yourself". + 4. What is the difference between a class method and an instance method? What is the difference between instance_eval and class_eval? + An instance method has access to and can maniuplate the date of a particular instance of a class. A class method is associated iwth the class itself and has no instance of an object (unless an instance is passed into it, or it accesses some global instance variable). + + instance_eval and class_eval (and module_eval) let you set 'self' to any arbitrary object, evaluate the code in a block with that new 'self', and when done the true self is restored. + 5. What is the difference between a singleton class and a singleton method? + A singleton method is a method that was dynamically added to a particular instance of an object. Other object of the same class will not have that singleton method. + + A singleton class (or metaclass) is a class that can have class methods, but no instance of the class can be created. + diff --git a/week8/exercises/couch.rb b/week8/exercises/couch.rb index b32ea96..580cf70 100644 --- a/week8/exercises/couch.rb +++ b/week8/exercises/couch.rb @@ -11,16 +11,29 @@ def initialize pillows, cushions, dogs end end - def pillow_colors - @pillows.map &:to_s - end + # def pillow_colors + # @pillows.map &:to_s + # end - def cushions_colors - @cushions.map &:to_s - end + # def cushions_colors + # @cushions.map &:to_s + # end def dog_names @dogs.map &:to_s end + [:pillows, :cushions].each do |s| + n = "" + if s == :pillows + n = s.to_s.chomp('s') + else + n = s.to_s + end + define_method("#{n}_colors") do + instance_variable_get("@#{s}").map &:to_s + end + + end + end \ No newline at end of file