diff --git a/week1/homework/questions.txt b/week1/homework/questions.txt index 2257bb9..95092d4 100644 --- a/week1/homework/questions.txt +++ b/week1/homework/questions.txt @@ -3,13 +3,22 @@ Chapter 3 Classes, Objects, and Variables p.86-90 Strings (Strings section in Chapter 6 Standard Types) 1. What is an object? +Objects are specific things that are known. For example, the title of a book. Classes are then created to categorize those known things into groups which share similar characteristics. 2. What is a variable? +A variable is a reference to an object, but it is not an object itself. 3. What is the difference between an object and a class? +All classes function as objects in Ruby, but not all objects are classes. Classes classify groups of things based on similar characertistics. In the assigned reading's bookstore example, certain genres (such as thrillers, romance, literary fiction, etc.) could represent classes that contain books (things/objects). A specific book within one of those classes would be an instance of that class. For example, the book "The Hunger Games" is categorized as Young Adult at bookstores, so this particular book (an object) would be an instance of the class YoungAdult. 4. What is a String? +A string is an object of class String that can hold sequences of printable characters or binary data. + 5. What are three messages that I can send to a string object? Hint: think methods +Squeeze, chomp, and split. Squeeze trims runs of repeated characters, which makes it good for removing extra spaces in a string. Chomp removes white space that occurs before or after a specified string. Split separates a string into two or more pieces. + 6. What are two ways of defining a String literal? Bonus: What is the difference between them? + +Single quotes (' ') and double quotes (" ") can both be used to define String literals. Single quote strings support two escape sequences: double backslash (\\), which prints a backslash within a string (\), and a backslash followed by a single quote (\'), which prints a single quote/apostrophe within the string ('I\'m going to the store today' => I'm going to the store today). Double quotes support even more escape sequences, including newline character (\n), which can be used to signify the end of a line. \ No newline at end of file diff --git a/week1/homework/strings_and_rspec_spec.rb b/week1/homework/strings_and_rspec_spec.rb index ea79e4c..69dcac8 100644 --- a/week1/homework/strings_and_rspec_spec.rb +++ b/week1/homework/strings_and_rspec_spec.rb @@ -12,14 +12,15 @@ before(:all) do @my_string = "Renée is a fun teacher. Ruby is a really cool programming language" end - it "should be able to count the charaters" - it "should be able to split on the . charater" do - pending - result = #do something with @my_string here + it "should be able to count the characters" do + @my_string.should have(@my_string.length).characters + end + it "should be able to split on the . character" do + result = @my_string.chomp.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"))' + @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..5702353 100644 --- a/week2/homework/questions.txt +++ b/week2/homework/questions.txt @@ -4,10 +4,20 @@ Sharing Functionality: Inheritance, Modules, and Mixins 1. What is the difference between a Hash and an Array? +An array is an ordered list of objects that's indexed using integers. A hash is collection of key/value pairs. Hashes are indexed with objects of any type (symbols, strings, regular expressions, etc.). + 2. When would you use an Array over a Hash and vice versa? +Use hashes when indexing requires objects other than integers (i.e. strings, symbols, expressions, etc.). Use arrays when indexing with integers. + 3. What is a module? Enumerable is a built in Ruby module, what is it? +Modules are a way of grouping together methods, classes, and constants. They provide a namespace and prevent names clashes and support the mixin facility. Enumerable enables the "each" iterator and allows collections within classes to be sorted, traversed, etc. + 4. Can you inherit more than one thing in Ruby? How could you get around this problem? +Ruby doesn't support multiple inheritance. You could get around this problem by using mixins. + 5. What is the difference between a Module and a Class? + +Classes can inherit behavior and can be the base for inheritance. They can also be instantiated. Modules have no inheritance and cannot be instantiated. diff --git a/week2/homework/simon_says.rb b/week2/homework/simon_says.rb new file mode 100644 index 0000000..25e66a5 --- /dev/null +++ b/week2/homework/simon_says.rb @@ -0,0 +1,21 @@ +module SimonSays + def echo(string) + string + end + + def shout(string) + string.upcase + end + + def first_word(string) + string.split.first + end + + def start_of_word(string,i) + string[0...i] + end + + def repeat(string, x=2) + ([string]*x).join(' ') + 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..59ff7d6 --- /dev/null +++ b/week3/homework/calculator.rb @@ -0,0 +1,22 @@ +class Calculator + def sum(array) + array.inject(0){|sum, x| sum +x} + end + + def multiply(*numbers) + puts numbers.inspect + numbers.flatten.inject(:*) + end + + def pow(base, p) + pow_fac(base, p) + end + + def fac(n) + pow_fac(n) + 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/questions.txt b/week3/homework/questions.txt index dfb158d..4652cc6 100644 --- a/week3/homework/questions.txt +++ b/week3/homework/questions.txt @@ -6,10 +6,35 @@ Please Read: 1. What is a symbol? +A Ruby symbol is an identifier corresponding to a string of characters, often a name. + 2. What is the difference between a symbol and a string? +Symbols are immutable. Strings are mutable. + 3. What is a block and how do I call a block? +A block is simply a chunk of code enclosed between either braces or the keywords do and +end. You can call a block within a method using yield. + 4. How do I pass a block to a method? What is the method signature? +There are two mains ways to pass a block to a method. You can define the block after the method call with either the curly bracket enclosure {} or the do/end syntax. Or you can add a block to a method by putting an ampersand before the variable name. + +An example of defining the block after the method call: + +string.split {|s| puts s} + +An example of adding a block to a method with an ampersand: + +def your_method(&your_block) +your_block.call +end + 5. Where would you use regular expressions? + +Regular expressions are used for pattern matching and replacing/changing strings. Below are three examples of ways you can use regular expressions: + + You can use them to test a string to see whether it matches a pattern. + You can use them to extract from a string the sections that match all or part of a pattern. + You can use them to change the string, replacing parts that match a pattern. diff --git a/week4/homework/questions.txt b/week4/homework/questions.txt index 187b3d3..42d2c09 100644 --- a/week4/homework/questions.txt +++ b/week4/homework/questions.txt @@ -4,11 +4,23 @@ The Rake Gem: http://rake.rubyforge.org/ 1. How does Ruby read files? +Ruby reads files by using the File class (a subclass of the IO class) and its associated methods (File.open, File.gets, etc.). + 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 directories in the underlying file system. They provide a variety of ways to list directories and their contents. + 4. What is an IO object? +An IO object is a bidirectional channel between a Ruby program and some external source. + 5. What is rake and what is it used for? What is a rake task? +Rake (also known as Ruby Make) is a build language written in Ruby that's used to define a set of tasks and the dependencies between them in a file. Rake tasks are the main unit of work in a Rakefile and have a name (usually a symbol or string), a list of prerequisites (more symbols or strings), and a list of actions (given as a block). + diff --git a/week4/homework/worker.rb b/week4/homework/worker.rb new file mode 100644 index 0000000..0b7a708 --- /dev/null +++ b/week4/homework/worker.rb @@ -0,0 +1,7 @@ +module Worker + def self.work t = 1 + r = nil + t.times { r = yield } + r + end +end diff --git a/week7/homework/features/step_definitions/pirate.rb b/week7/homework/features/step_definitions/pirate.rb new file mode 100644 index 0000000..cd4a163 --- /dev/null +++ b/week7/homework/features/step_definitions/pirate.rb @@ -0,0 +1,17 @@ +class PirateTranslator + 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 +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..9213581 --- /dev/null +++ b/week7/homework/features/step_definitions/tic-tac-toe.rb @@ -0,0 +1,129 @@ +class TicTacToe + SYMBOLS = [:X,:O] + attr_accessor :player, :board + + def initialize(current_player=nil,player_sym=nil) + setup_board + @current_player = current_player || [:computer, :player].sample + choose_player_symbol(player_sym) + end + + def computer_symbol + @player_symbol[:computer] + end + + def player_symbol + @player_symbol[:player] + end + + def current_player + {:computer => "Computer", + :player => @player}[@current_player] + end + + def welcome_player + "Welcome #{@player}" + end + + def indicate_palyer_turn + puts "#{@player}'s Move:" + end + + def get_player_move + gets.chomp + end + + def player_move + move = get_player_move.to_sym + until open_spots.include?(move) + move = get_player_move.to_sym + end + @board[move] = player_symbol + @current_player = :computer + move + end + + def computer_move + move = get_computer_move + @board[move] = computer_symbol + @current_player = :player + move + end + + def get_computer_move + @board.select{|k,v| v.to_s.strip.empty?}.map{|k,v| k}.sample + end + + def current_state + row1 = "#{@board[:A1]}|#{@board[:A2]}|#{@board[:A3]}\n" + row2 = "#{@board[:B1]}|#{@board[:B2]}|#{@board[:B3]}\n" + row3 = "#{@board[:C1]}|#{@board[:C2]}|#{@board[:C3]}\n" + row1 + "-"*row1.size+"\n"+ + row2 + "-"*row2.size+"\n"+ + row3 + "-"*row3.size+"\n"+ + "******" + end + + def determine_winner + p_spots = @board.select{|k,v| v==player_symbol} + c_spots = @board.select{|k,v| v==computer_symbol} + + player_spots = p_spots.map{|k,v| {k[0].to_sym => k[1].to_i} } + computer_spots = c_spots.map{|k,v| {k[0].to_sym => k[1].to_i} } + @player_win = false + @computer_win = false + [:A, :B, :C].each do |l| + return if @player_win = player_spots.map{|i| i[l]}.reject{|f| f.nil?}.sort == [1,2,3] + return if @computer_win = computer_spots.map{|i| i[l]}.reject{|f| f.nil?}.sort == [1,2,3] + end + + [1,2,3].each do |l| + return if @player_win = player_spots.map{|i| i.invert[l]}.reject{|f| f.nil?}.sort == [:A,:B,:C] + return if @computer_win = computer_spots.map{|i| i.invert[l]}.reject{|f| f.nil?}.sort == [:A,:B,:C] + end + + return if @player_win = p_spots.keys.sort.reject{|r| ![:A1,:B2,:C3].include? r} == [:A1,:B2,:C3] + return if @player_win = p_spots.keys.sort.reject{|r| ![:A3,:B2,:C1].include? r} == [:A3,:B2,:C1] + return if @computer_win = c_spots.keys.sort.reject{|r| ![:A1,:B2,:C3].include? r} == [:A1,:B2,:C3] + return if @computer_win = c_spots.keys.sort.reject{|r| ![:A3,:B2,:C1].include? r} == [:A3,:B2,:C1] + end + + def player_won? + !!@player_win + end + + def computer_won? + !!@computer_win + end + + def draw? + !player_won? && !computer_won? + end + + def over? + player_won? || computer_won? || !spots_open? + end + + def spots_open? + !open_spots.empty? + end + + def open_spots + @board.select{|k,v| v.to_s.strip.empty?}.map{|k,v| k} + end + +private + def setup_board + @board = {:A1 => ' ', :A2 => ' ', :A3 => ' ', + :B1 => ' ', :B2 => ' ', :B3 => ' ', + :C1 => ' ', :C2 => ' ', :C3 => ' '} + end + + def choose_player_symbol(player_sym=nil) + player_sym ||= SYMBOLS.sample + @player_symbol = { + :computer => SYMBOLS.reject{|s| s==player_sym}.first, + :player => player_sym + } + end +end diff --git a/week7/homework/questions.txt b/week7/homework/questions.txt index d55387d..1c4009c 100644 --- a/week7/homework/questions.txt +++ b/week7/homework/questions.txt @@ -3,7 +3,22 @@ Please Read Chapters 23 and 24 DuckTyping and MetaProgramming Questions: 1. What is method_missing and how can it be used? -2. What is and Eigenclass and what is it used for? Where Do Singleton methods live? -3. When would you use DuckTypeing? How would you use it to improve your code? + +When Ruby can't find a called method in the object's class, superclass, etc., it calls method_missing, a method that raises an exception (either a NoMethodError or a NameError depending on the circumstances). Method_missing can be used to intercept every use of an undefined method and handle it. It can also intercept all calls, but it handles only some of them. + +2. What is a Eigenclass and what is it used for? Where Do Singleton methods live? + +A eigenclass is an anonymous class (also known as a singleton class) located between an object and the object's original class that defines methods for a specific object. Singleton methods live within the eigenclass/singleton class. + +3. When would you use DuckTyping? How would you use it to improve your code? + +With DuckTyping, an object's type is defined by its behavior (i.e. what it can do) and not its class. In other words, if quacks like a duck, walks like a duck, and looks like a duck, it's a duck regardless of what its class really is. I'd use DuckTyping for when I wanted to avoid type-related errors, improve garbage collection, and increase my productivity by writing less code. Using DuckTyping would allow me to avoid testing a class in order to determine its type. Without the check, the method I'm working with will be more felxible, and I could pass it to an array, a string, a file, or any other object that appends using <<, and it would just work. + 4. What is the difference between a class method and an instance method? What is the difference between instance_eval and class_eval? + +Class methods are methods that are called on a class. Instance methods, on the other hand, are methods that are called on an instance of a class. Class_eval and instance_eval differ in the way they set up the environment for method definition. Class_eval sets things up as if you were in the body of a class definition, so method definitions will define instance methods. Instance_eval, on the other hand, acts as if you were working inside the singleton class of self. Any methods you define will become class methods. + 5. What is the difference between a singleton class and a singleton method? + +A singleton method is a method that belongs to a single object. A singleton class is a class which defines a single object. +