diff --git a/week1/exercises/roster.txt b/week1/exercises/roster.txt index af85dab..df8b837 100644 --- a/week1/exercises/roster.txt +++ b/week1/exercises/roster.txt @@ -20,7 +20,7 @@ 18, Jordan Mayer, Jordan2210@gmail.com, jordanmayer, n/a, Jordanm 19, Martin Nash, martin.j.nash@gmail.com, MartinJNash, @MartinJNash, martin.j.nash 20, Thomas Osborn, trosborn@gmail.com, trosborn, joosushi, trosborn -21, Vy Nguyen, vnguye36@gmail.com, github.com/shrsp +21, Vy Nguyen, vnguye36@gmail.com, github.com/kvm79 22, Chris Montes, chrismontes@about.me, mandelbro, @chrismontes, chrismontes 23,Alicia Quilez, alienor18@yahoo.com 24,Pat Remy, pat@remy.cc, premy52, , subs@remy.cc diff --git a/week1/homework/homework.rtf b/week1/homework/homework.rtf new file mode 100644 index 0000000..3488a57 --- /dev/null +++ b/week1/homework/homework.rtf @@ -0,0 +1,10 @@ +{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf360 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;} +\margl1440\margr1440\vieww9000\viewh8400\viewkind0 +\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural + +\f0\fs24 \cf0 read chapter 3 classes, objects and variables\ +pgs 86-90\ +answer questions in homework folder\ +make spec pass strings_and_rspec_spec.rb} \ No newline at end of file diff --git a/week1/homework/questions.txt b/week1/homework/questions.txt index bd581a6..fe35a45 100644 --- a/week1/homework/questions.txt +++ b/week1/homework/questions.txt @@ -4,12 +4,31 @@ p.86-90 Strings (Strings section in Chapter 6 Standard Types) 1. What is an object? + Objects are instances of the class. Objects have a state (attributes), behavior (methods), and identity (unique identifier). Objects are instances that have identical methods but differing data. + 2. What is a variable? + Variables are used to keep track of objects. Each variable holds a reference to an object. Ruby supports four types of variables: Global Variables, Instance Variables, Class Variables and Local Variables + 3. What is the difference between an object and a class? + Objects contain information about something in the program. Objects provide actions (functions and methods) which manipulate that information. + + Classes contains the blue print of how to build an object and information about what defines an object. + + For example, recipe for a blueberry pie. Recipe is the class and blueberry pie is the object. + 4. What is a String? -5. What are three messages that I can send to a string object? Hint: think methods + Strings are objects of class String. Stings are simply sequence of characters and are created using string literals - sequences of characters between delimiters. Strings can also hold binary data. +5. What are three messages that I can send to a string object? Hint: think methods + 1. %q (single-quote) + 2. %Q (double-quote) + 3. here documents + 6. What are two ways of defining a String literal? Bonus: What is the difference between the two? + + Double-quoted stings allow substitution and backlash notation but single-quoted strings don't allow substitution and allow backlash notation only for \\ and \'. + + \ 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..e294143 100644 --- a/week1/homework/strings_and_rspec_spec.rb +++ b/week1/homework/strings_and_rspec_spec.rb @@ -12,14 +12,17 @@ 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 count the charaters" do + @my_string.count("Renée is a fun teacher. Ruby is a really cool programming language") + 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"))' + #pending 'helpful hint: should eq (Encoding.find("UTF-8"))' + @my_string.encode("UTF-8") + end end end diff --git a/week2/homework/questions.txt b/week2/homework/questions.txt index 939e42d..1783d95 100644 --- a/week2/homework/questions.txt +++ b/week2/homework/questions.txt @@ -4,10 +4,26 @@ Sharing Functionality: Inheritance, Modules, and Mixins 1. What is the difference between a Hash and an Array? + An array is an ordered, integer-indexed collections of objects. A hash is an unordered, object-indexed collection of key/value pairs and indexing is done via arbitrary keys of any object: strings, symbols, regular expressions (not an integer index). + 2. When would you use an Array over a Hash and vice versa? + Use arrays when order matters and use hashes when you want to refer to objects by their labels. + 3. What is a module? Enumerable is a built in Ruby module, what is it? -4. Can you inherit more than one thing in Ruby? How could you get around this problem? + A module is a way of grouping methods, classes and constants. Modules provide a namespace and prevent name clashes. Modules support the mixing facility. + Enumerable provides collection classes with several traversal and searching methods, and with the ability to sort + +4. Can you inherit more than one thing in Ruby? How could get around this problem? + Ruby has single inheritance meaning each class has one parent class. Ruby can simulate multiple inheritance using modules mixins. Mixins allow you to write code in one place and inject that code into multiple classes. + 5. What is the difference between a Module and a Class? + + Modules cannot be instantiated, uses mixing and consist of methods, constants and classes. Modules don't have inheritance and provide methods that can be used across multiple classes. + + Classes can be instantiated and consist of methods, constants and variables. Classes inherits behavior. + + Classes are about objects while modules are about functions. + diff --git a/week2/homework/simon_says.rb b/week2/homework/simon_says.rb new file mode 100644 index 0000000..98cb709 --- /dev/null +++ b/week2/homework/simon_says.rb @@ -0,0 +1,31 @@ +module SimonSays + + # return string + def echo(string) + string + end + + # return string and convert string to caps + def shout(string) + string.upcase + end + + # repeat a string n times + def repeat(string, int = 2) + ([string] * int).join (' ') + end + + # return start of word + def start_of_word(string, char) + string.slice(0, char) + end + + # return first word + def first_word(string) + word = 1 + @string = string + @string.split[0...word].join(' ') + end + +end + diff --git a/week2/homework/simon_says_spec.rb b/week2/homework/simon_says_spec.rb index 7f329e5..8def7d3 100644 --- a/week2/homework/simon_says_spec.rb +++ b/week2/homework/simon_says_spec.rb @@ -2,7 +2,11 @@ require "./simon_says.rb" describe SimonSays do - include SimonSays # Hint: Inclusion is different than SimonSays.new (read about modules) + + # Hint: Inclusion is different than SimonSays.new (read about modules) + # Can include a module within a class definition. + # Mixin. All module instances methods in SimonSays are now available as methods in the class. + include SimonSays # Hint: We are just calling methods, we are not passing a message to a SimonSays object. it "should echo hello" do diff --git a/week3/homework/calculator.rb b/week3/homework/calculator.rb new file mode 100644 index 0000000..4a13e2a --- /dev/null +++ b/week3/homework/calculator.rb @@ -0,0 +1,65 @@ +class Calculator + + # sum of array of numbers + # converts to an integer + # If blank, then converts to zero + # inject "accummulate" + def sum(val) + val.inject(0){|sum, n| sum + n } + #val.inject(0, :+) + end + +=begin + def sum val + result = 0 + #loop thru array + val.each do |i| + result += i + end + result + end +=end + + # multiply array of numbers + # * splat means any number of arguments + # flatten method: pass in as many arguments as you want, + # flatten method: for every element that is an array, extract its elements into the new array + # flatten method: always going to get back a single array + def multiply(*val) + val.flatten.inject(1, :*) + end + + # raises one number to the power of another number + def pow (base, exp) + # base**exp + ([base] * exp).inject(:*) + end + + # computes factorials + # recursive defintion: a method calls on itself inside itself + # without recursion: num.inject {|product, n| product * n } + def fac(num) + if num == 0 + 1 + else + num * fac(num - 1) + end + end + +=begin + def fac(num) + return 1 if num==0 + num * fac(num-1) + end + + def fac(num) + # a range of array + # (1..n).to_a.inject(:*) + + # another option + product = 1 + 1.upto(n){|i| product += 1} + product + end +=end +end diff --git a/week3/homework/calculator_spec.rb b/week3/homework/calculator_spec.rb index 5a418ed..c74d20b 100644 --- a/week3/homework/calculator_spec.rb +++ b/week3/homework/calculator_spec.rb @@ -2,6 +2,7 @@ describe Calculator do + # create new instance of Calculator class before do @calculator = Calculator.new end @@ -29,17 +30,19 @@ describe "#multiply" do it "multiplies two numbers" do @calculator.multiply(2,2).should eq 4 - end + end it "multiplies an array of numbers" do @calculator.multiply([2,2]).should eq 4 end 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 + describe "#pow" do + it "raises one number to the power of another number" do + p = 1 + 32.times{ p *= 2 } + @calculator.pow(2,32).should eq p + end end # http://en.wikipedia.org/wiki/Factorial diff --git a/week3/homework/questions.txt b/week3/homework/questions.txt index dfb158d..d9005d6 100644 --- a/week3/homework/questions.txt +++ b/week3/homework/questions.txt @@ -5,11 +5,27 @@ Please Read: - Chapter 22 The Ruby Language: basic types (symbols), variables and constants 1. What is a symbol? + + Symbols are objects that represent names and strings. They are generated using the :name and :string literals syntax. A particular name or string will always generate the same symbol, regardless of the context or meaning of that name. 2. What is the difference between a symbol and a string? + Symbols are immutable and strings are mutable. Mutable objects can be changed after assignment while immutable objects can only be overwritten. Symbols stay in memory throughout the programs operation, strings have object_ids to have its own place in memory. Symbols are faster then strings in how they are stored, used and how they are compared. + 3. What is a block and how do I call a block? + A block is a closure; it's a chunk of code attached to a method. It remembers the context in which it was defined, and it uses that context whenever it's called. The context includes the value of self, the constants, the class variables, the local variables, and any captured block. + A block can be called using the "yield" keyword; parameters passed to "yield" will be assigned to arguments in the block. + 4. How do I pass a block to a method? What is the method signature? + 1. Use "yield" keyword. + 2. Prefix the last argument in a method signature with an ampersand which will then create a Proc object from any block passed in. + The method signature is the name of the method name. + 5. Where would you use regular expressions? + + Use regular expressions to: + 1. test a string to see whether it matches a pattern + 2. extract sections of a string that match all or part of a pattern + 3. change the string, replacing parts that match a pattern diff --git a/week4/exercises/worker.rb b/week4/exercises/worker.rb new file mode 100644 index 0000000..2c9b46d --- /dev/null +++ b/week4/exercises/worker.rb @@ -0,0 +1,18 @@ +class Worker + # self. class level method + # (n=1) gives it a default value bc it's optional + # represent number of times code should be running + def self.work(n=1) + (0..n).reduce { yield } + + #accumulation of + #result = nil + #n.times = {result = yield} + #result + + #enumerator: an object, foundation of :each method + #allows us to traverse collection of things (iterator) + #inject sets to nil and give a value to our block each time we call the block + #n.times.inject{yield} + end +end diff --git a/week4/homework/questions.txt b/week4/homework/questions.txt index bc1ab7c..8e274b3 100644 --- a/week4/homework/questions.txt +++ b/week4/homework/questions.txt @@ -3,7 +3,27 @@ Chapter 10 Basic Input and Output The Rake Gem: http://rake.rubyforge.org/ 1. How does Ruby read files? + + By the File class, which allows for the use of the I/O methods. + 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 + + puts File.read("my_output.txt") + 3. What is the Directory class and what is it used for? + + The Dictionary class is a type of ordered Hash, which keeps it's contents in a customizable order. + 4. What is an IO object? + + A bidirectional channel between a Ruby program and some external resource. This base class is subclassed by classes File and BasicSocket and handles input and output. + 5. What is rake and what is it used for? What is a rake task? + + It's a Ruby build program with capabilities similar to make. Rake enables you to define a set of tasks and the dependencies between them in a file. + + Tasks are the main unit of work in a Rakefile. Tasks have a name (usually given as a symbol or a string), a list of prerequisites (more symbols or strings) and a list of actions (given as a block). For example, file or directories tasks create files and directories. diff --git a/week5/exercises/Rakefile.rb b/week5/exercises/Rakefile.rb new file mode 100644 index 0000000..1069129 --- /dev/null +++ b/week5/exercises/Rakefile.rb @@ -0,0 +1,28 @@ +desc "print all names" +task :print_names do + dir_name + File.open("names") +end + +desc "make student directories" +task :create_student_dirs => [:create_student_dirs] do + dir_name +end + +desc "make class directory" +task :create_class_dirs => [:create_class_dirs] do + dir_name +end + +desc "remove all directories" +task :remove_dirs => [:remove_dirs] do + dir_name +end + +def file_helper(file_name) + File.open(file_name) do |f| + f.each do |line| + yield line.chomp + end + end +end \ No newline at end of file diff --git a/week7/class_materials/cucumber/features/step_definitions/converter.rb b/week7/class_materials/cucumber/features/step_definitions/converter.rb index e37c629..de640b3 100644 --- a/week7/class_materials/cucumber/features/step_definitions/converter.rb +++ b/week7/class_materials/cucumber/features/step_definitions/converter.rb @@ -1,7 +1,8 @@ class Converter - def initialize(unit) - @unit = unit.to_f + # must accept celcius value + def initialize(cel_val) + @cel_val = cel_val.to_f end def type=(type) @@ -13,6 +14,6 @@ def convert end def Celsius_convertion - (@unit * (9.0/5.0) + 32.0).round(1) + (@cel_val * (9.0/5.0) + 32.0).round(1) 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..b7368bf --- /dev/null +++ b/week7/homework/features/step_definitions/pirate.rb @@ -0,0 +1,38 @@ +class PirateTranslator +=begin + PIRATE_TRANSLATOR = { + "Hello Friend" => "Ahoy Matey\n Shiber Me Timbers You Scurvey Dogs!!" + } + + # step 1: class PirateTranslator + # step 2: define say + def say(arg) + @pirate = arg + end + + # steps 3-5: define translate + def translate + @result = '' + @result = PIRATE_TRANSLATOR[@pirate] + end +=end + + PIRATE_TRANSLATOR = { + hello_friend: "Ahoy Matey" + } + + def say(something) + @said = something + end + + def translate + pirate_lookup(@said) + "\n Shiber Me Timbers You Scurvey Dogs!!" + end + + private + + def pirate_lookup (said) + key = said.gsub(' ','_').downcase.to_sym + PIRATE_TRANSLATOR[key] + end +end diff --git a/week7/homework/features/step_definitions/pirate_steps.rb b/week7/homework/features/step_definitions/pirate_steps.rb index faf1a7f..0465912 100644 --- a/week7/homework/features/step_definitions/pirate_steps.rb +++ b/week7/homework/features/step_definitions/pirate_steps.rb @@ -1,5 +1,8 @@ Gangway /^I have a (\w+)$/ do |arg| + # @translator = Kernel.const_get(arg).new + # PirateTranslator object + @translator = PirateTranslator.new end Blimey /^I (\w+) '(.+)'$/ do |method, arg| 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..f851a00 100644 --- a/week7/homework/features/step_definitions/tic-tac-toe-steps.rb +++ b/week7/homework/features/step_definitions/tic-tac-toe-steps.rb @@ -35,7 +35,7 @@ Then /^the computer prints "(.*?)"$/ do |arg1| @game.should_receive(:puts).with(arg1) - @game.indicate_palyer_turn + @game.indicate_player_turn end Then /^waits for my input of "(.*?)"$/ do |arg1| @@ -43,7 +43,7 @@ @game.get_player_move end -Given /^it is the computer's turn$/ do +Given /^it is the computers turn$/ do @game = TicTacToe.new(:computer, :O) @game.current_player.should eq "Computer" end @@ -121,4 +121,4 @@ @game.board[arg1.to_sym] = ' ' @game.should_receive(:get_player_move).twice.and_return(@taken_spot, arg1) @game.player_move.should eq arg1.to_sym -end +end \ No newline at end of file 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..69f99b6 --- /dev/null +++ b/week7/homework/features/step_definitions/tic-tac-toe.rb @@ -0,0 +1,138 @@ +class TicTacToe + + attr_accessor :player, + :player_symbol, + :computer_symbol, + :player_move, + :turn, + :board, + :winning_combo + + SYMBOLS = [:X,:O] + + def initialize(com = :computer, player_symbol= :X, player = "") + @turn = com + @player_symbol = player_symbol + @player = player + @board = Hash.new("") + end + + # define 9 spots on board + def board + @board = { + "a1"=>'',"a2"=>'',"a3"=>'', + "b1"=>'',"b2"=>'',"b3"=>'', + "c1"=>'',"c2"=>'',"c3"=>'' + } + end + + # return welcome message + def welcome_player + @welcome_player = "Welcome #{@player}" + end + + # define X and O + def computer_symbol + puts @player_symbol + if(@player_symbol == :O) + :X + else + :O + end + end + + # return current player + def current_player + if (@turn == :computer) + return "Computer" + else + @player + end + end + + # print player's move + def indicate_player_turn + puts "#{@player}'s Move:" + end + + # get player's input + def get_player_move(player_move = "") + player_move.chomp + end + + # computer chooses random spot + def computer_move + c_move = open_spots.sample + @board[c_move] = @computer_symbol.to_s + @turn = :player + end + + # player's turn + def player_move + p_move = get_player_move.to_sym + # if spot is open player's move, otherwise computer's move + if open_spots.include? p_move + c_move = p_move + else + @board[c_move] = @player_symbol.to_s + @turn = :computer + end + @player_move + end + + # define open spots + def open_spots + @board.select{|k,v| v.to_s.strip.empty?}.map{|k,v| k} + end + + # checks open spots + def spots_open? + !open_spots.empty? + end + + # define winning combinations + def winning_combo symbol + @winning_combo = [ + ["a1","a2","a3"], + ["b1","b2","b3"], + ["c1","c2","c3"], + ["a1","b1","c1"], + ["a2","b2","c2"], + ["a3","b3","c3"], + ["a1","b2","c3"], + ["c1","b2","a3"] + ] + end + + # determine winner + def determine_winner + @winner = false + winning_game = winning_combo symbol + @game_over = winning_game + @winner = winning_game + if (spots_open? == false and @winner == false) + @game_over = true + end + end + + # if player wins + def player_won? + @winner == @player_symbol + end + + #if computer wins + def computer_won? + @winner == @computer_symbol + end + + #if game is over + def over? + @game_over = true + end + + #if game is a draw + def draw? + @game_over == true and @winner == false + end + +end diff --git a/week7/homework/questions.txt b/week7/homework/questions.txt index d55387d..7629cfe 100644 --- a/week7/homework/questions.txt +++ b/week7/homework/questions.txt @@ -3,7 +3,45 @@ Please Read Chapters 23 and 24 DuckTyping and MetaProgramming Questions: 1. What is method_missing and how can it be used? +<<<<<<< HEAD + + - It's a built-in hook method (sometimes called a callback). There are two main uses for the method_missing hook. The first is to intercept every use of an undefined method and handles it (either with NoMethodError or a NameError). The second is to intercept all calls but handles only some of them. + + +2. What is and Eigenclass and what is it used for? Where Do Singleton methods live? + + - Eigenclass is a dynamically created anonymous class that holds the object's singleton methods. It assumes the role of the object's class and the original class is re-designated as the superclass of that anonymous class. + + - Singleton methods reside inside an object's singleton class and can be accessed using Ruby's class << an_object notation. + + +3. When would you use DuckTypeing? How would you use it to improve your code? + + - Duck typing is convenient for testing and writing flexible application code. + - When using duck typing remember: + 1. an object's type is determined by what it can do, not by its class + 2. respond_to? fails when you are using method_missing to catch and respond to method calls. The only way to be sure that respond_to? is not deceiving you is to call the method + + 3. use the Types framework to make sure you're never passing something weird from somewhere in your code + + +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 and instance methods are methods that are called on an instance of a class. Class methods are for anything that does not deal with an individual instance of a class. Instance methods only work with an instance and thus you have to create a new instance to use them (Bar.new). + + - instance_eval can be used on any object, even class objects. If it's used on an instance of an object then it evals on that instance creating an instance method. And if it's used on a class object then it evals on the class creating a class method. + + - class_eval can only be called on classes or module and it evils on the instances of the class/module creating instance methods. + + +5. What is the difference between a singleton class and a singleton method? + + - Singleton method: a method which belongs to a single object rather than to an entire class and other objects. + + - Singleton class: a class which defines a single object +======= 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? 4. What is the difference between a class method and an instance method? What is the difference between instance_eval and class_eval? 5. What is the difference between a singleton class and a singleton method? +>>>>>>> 8b3b197baa14a59c207aca832acf7ce570e9e099