diff --git a/mid_term/even_number.rb b/mid_term/even_number.rb deleted file mode 100644 index fa9fc6e..0000000 --- a/mid_term/even_number.rb +++ /dev/null @@ -1,21 +0,0 @@ -class EvenNumber - include Comparable - attr_reader :value - - def self.new(value) - return false if value.odd? - super - end - - def initialize(value) - @value = value - end - - def succ - EvenNumber.new(@value + 2) - end - - def <=> (other) - @value <=> other.value - end -end \ No newline at end of file diff --git a/mid_term/even_number_spec.rb b/mid_term/even_number_spec.rb deleted file mode 100644 index 3e254c2..0000000 --- a/mid_term/even_number_spec.rb +++ /dev/null @@ -1,27 +0,0 @@ - # - 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 - # - Compare even numbers - # - Generate a range of even numbers - -require './even_number.rb' - -describe EvenNumber do - it "should only allow even numbers" do - EvenNumber.new(5).should be_false - end - - it "should get the next even number" do - EvenNumber.new(2).succ.should == EvenNumber.new(4) - end - - it "should compare even numbers" do - (EvenNumber.new(2) < EvenNumber.new(4)).should be_true - end - - it "should generate a range of even numbers" do - (EvenNumber.new(2)..EvenNumber.new(8)).should be_a Range - end -end \ No newline at end of file diff --git a/mid_term/mid_term_spec.rb b/mid_term/mid_term_spec.rb deleted file mode 100644 index 0556a97..0000000 --- a/mid_term/mid_term_spec.rb +++ /dev/null @@ -1,74 +0,0 @@ -require "#{File.dirname(__FILE__)}/turkey" - -describe Turkey do - - before do - @turkey = Turkey.new(10) - end - - it "should report the turkey weight" do - @turkey.weight.should equal 10 - end - - it "should be a kind of animal" do - @turkey.kind_of?(Animal).should be_true - end - - it "should gobble speak" do - @turkey.gobble_speak("Hello I Am a Turkey. Please Don't Eat Me.").should eq "Gobble Gobble Gobble gobble Gobble. Gobble Gobb'le Gobble Gobble." - end - -end - -require "#{File.dirname(__FILE__)}/thanksgiving_dinner" - -describe ThanksgivingDinner do - - before do - @t_dinner = ThanksgivingDinner.new(:vegan) - @t_dinner.guests = ["Aunt Petunia", "Uncle Vernon", "Aunt Marge", "Dudley", "Harry"] # I know I just made a British family celebrate Thanksgiving, but it could be worse: It could have been the 4th of July! :) - end - - it "should be a kind of dinner" do - @t_dinner.kind_of?(Dinner).should be_true - end - - # Use inject here - it "should sum the letters in each guest name for the seating chart size" do - @t_dinner.seating_chart_size.should eq 45 - end - - it "should provide a menu" do - @t_dinner.respond_to?(:menu).should be_true - end - - context "#menu" do - - it "should have a diet specified" do - @t_dinner.menu[:diet].should eq :vegan - end - - it "should have proteins" do - @t_dinner.menu[:proteins].should eq ["Tofurkey", "Hummus"] - end - - it "should have vegetables" do - @t_dinner.menu[:veggies].should eq [:ginger_carrots , :potatoes, :yams] - end - - # Dinners don't always have dessert, but ThanksgivingDinners always do! - it "should have desserts" do - @t_dinner.menu[:desserts].should eq({:pies => [:pumkin_pie], :other => ["Chocolate Moose"], :molds => [:cranberry, :mango, :cherry]}) - end - - end - - # Use String interpolation, collection methods, and string methods for these two examples - it "should return what is on the dinner menu" do - @t_dinner.whats_for_dinner.should eq "Tonight we have proteins Tofurkey and Hummus, and veggies Ginger Carrots, Potatoes, and Yams." - end - - it "should return what is on the dessert menu" do - @t_dinner.whats_for_dessert.should eq "Tonight we have 5 delicious desserts: Pumkin Pie, Chocolate Moose, and 3 molds: Cranberry and Mango and Cherry." - end -end diff --git a/mid_term/questions.txt b/mid_term/questions.txt deleted file mode 100644 index 0eba895..0000000 --- a/mid_term/questions.txt +++ /dev/null @@ -1,56 +0,0 @@ -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 - - Use .gitignore to ignore any files that are not relevant to the midterm - - 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 - - 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): - - What are the three uses of the curly brackets {} in Ruby? - 1. String interpolation: "#{1+1}" - 2. Hash instantiation: {:key => "value"} - 3. Block/lambda notation: {puts "hello"} - - - What is a regular expression and what is a common use for them? - A Regular expression is a pattern used to search text. A common use for them is for verifying the format of user input, like email addresses or phone numbers. - - - What is the difference between how a String, a symbol, a FixNum, and a Float are stored in Ruby? -A String is stored as a collection of characters (bytes) and the value of a string instance can change. A Symbol is a fixed name in ruby and is stored as an integer, so it takes up much less space than a string. A FixNum is an integer in Ruby and does not change its value. It is stored the same way as a symbol (you can think of symbols as Fixed Strings). Floats can have their value change and are stored like a string: each byte of the float is stored and can change individually. - - - Are these two statements equivalent? Why or Why Not? - 1. x, y = "hello", "hello" - 2. x = y = "hello" -No, in the first example x and y point to different objects, in the second they point to the same object. In # 2 if y changes x will change and vice versa. In # 1 if y changes x does not change and vice versa. - -- What is the difference between a Range and an Array? -A Range is an object that denotes a sequence between two objects (lower/min and higher/max). It does not store every element of the sequence, only the min and max. An array is an ordered list of many objects. Each object in an array is stored and cannot necessarily be determined by the prior object in the array. - -- Why would I use a Hash instead of an Array? -If I had data which I wanted to reference by meta-data instead of by order I would use a hash. For example, if I had a set of attributes common to a collection of things, I would use a hash so I could look across my data (or search) by the data's attribute dimensions. - -- What is your favorite thing about Ruby so far? -.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: - - Only allow even numbers - - 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 - -Mid-Term Spec (50pts): -- Make the tests pass. - - diff --git a/mid_term/thanksgiving_dinner.rb b/mid_term/thanksgiving_dinner.rb deleted file mode 100644 index 20b03ec..0000000 --- a/mid_term/thanksgiving_dinner.rb +++ /dev/null @@ -1,78 +0,0 @@ -class String - def titlecase - self.gsub(/\b\w/){|f| f.upcase} - end - - def humanize - self.gsub('_', ' ').titlecase - end -end - -module MenuFinder - MENUS = { - :vegan => { - :diet => :vegan, - :proteins => ["Tofurkey", "Hummus"], - :veggies => [:ginger_carrots , :potatoes, :yams] - } - } - def find_menu(kind) - MENUS[kind] - end - def find_dessert - @menu[:desserts] = {:pies => [:pumkin_pie], - :other => ["Chocolate Moose"], - :molds => [:cranberry, :mango, :cherry]} - end -end - -class Dinner - include MenuFinder - attr_accessor :menu, :guests, :kind - def initialize(kind) - @kind = kind - @menu = find_menu(kind) - end - def seating_chart_size - guests.inject(0){|sum,g| sum += g.size} - end - - def proteins - @menu[:proteins].map{|w| w.titlecase}.join(' and ') - end - - def veggies - @menu[:veggies].map{|w| w.to_s.humanize}.join(', ').gsub(/, \w*\z/){|w| w.gsub(',', ', and')} - end - - def whats_for_dinner - "Tonight we have proteins #{proteins}, and veggies #{veggies}." - end -end - -class ThanksgivingDinner < Dinner - def number_of_desserts - @menu[:desserts].map{|k,v| v}.flatten.count - end - - def pies - @menu[:desserts][:pies].map{|s| s.to_s.humanize}.join(',') - end - - def other - @menu[:desserts][:other].join(',') - end - - def number_of_molds - @menu[:desserts][:molds].count - end - - def molds - @menu[:desserts][:molds].map{|s| s.to_s.titlecase}.join(' and ') - end - - def whats_for_dessert - find_dessert - "Tonight we have #{number_of_desserts} delicious desserts: #{pies}, #{other}, and #{number_of_molds} molds: #{molds}." - end -end diff --git a/mid_term/turkey.rb b/mid_term/turkey.rb deleted file mode 100644 index 38498fb..0000000 --- a/mid_term/turkey.rb +++ /dev/null @@ -1,24 +0,0 @@ -class Animal -end -class Turkey < Animal - attr_accessor :weight - def initialize(weight) - @weight = weight - end - - def gobble_speak(monkey_talk) - monkey_talk.gsub(/\b\w*/) do |w| - if w[0] =~ /[A-Z]/ - "Gobble" - elsif w[0] =~ /[a-z]/ - "gobble" - end - end.gsub(/\b\w*'\w*\b/) do |w| - if w[0]=='G' - "Gobb'le" - else - "gobb'le" - end - end - end -end diff --git a/mid_term/wish_list.rb b/mid_term/wish_list.rb deleted file mode 100644 index 0677f36..0000000 --- a/mid_term/wish_list.rb +++ /dev/null @@ -1,9 +0,0 @@ -class WishList - include Enumerable - attr_accessor :wishes - def each - @wishes.each_with_index do |w,i| - yield "#{i+1}. #{w}" - end - end -end \ No newline at end of file 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/test_gem/dp_test_gem.gemspec b/test_gem/dp_test_gem.gemspec new file mode 100644 index 0000000..1c7ba85 --- /dev/null +++ b/test_gem/dp_test_gem.gemspec @@ -0,0 +1,11 @@ +Gem::Specification.new do |s| + s.name = 'dp_test_gem' + s.version = '0.0.1' + s.date = '2012-11-19' + s.summary = 'gettin crazy with test gems' + s.description = 'a tool to help me understand gem creation' + s.authors = ["danny pham"] + s.email = 'pham.danny.t@gmail.com' + s.homepage = 'http://rubygems.org/gems/test_gem' + s.files = ["lib/dp_test_gem.rb"] +end diff --git a/test_gem/lib/dp_test_gem.rb b/test_gem/lib/dp_test_gem.rb new file mode 100644 index 0000000..e1267f8 --- /dev/null +++ b/test_gem/lib/dp_test_gem.rb @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby + +puts "hello gem!" diff --git a/week1/homework/questions.txt b/week1/homework/questions.txt index 0adfd69..cefabc7 100644 --- a/week1/homework/questions.txt +++ b/week1/homework/questions.txt @@ -1,3 +1,19 @@ +<<<<<<< HEAD +1. What is an object? +An object is an instance of a class +2. What is a variable? +With Ruby, it is a reference to an object +3. What is the difference between an object and a class? +an object is a specific creation of related state and behavior created with the blueprint, or its class +4. What is a String? +String is a class so a string is an instance of String. A string represents text. +5. What are three messages that I can send to a string object? Hint: think methods +dup, freeze, [](0) +6. What are two ways of defining a String literal? +with single quotations and with double quotations +Bonus: What is the difference between the two? +double quotations allow for interpolation and more escape sequences +======= Please read: Chapter 3 Classes, Objects, and Variables p.90-94 Strings @@ -22,3 +38,4 @@ split - returns an array of strings made up of the original string separated on 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. +>>>>>>> 476e4b543ee68aad8bb809afdfe2207afd39e8e5 diff --git a/week1/homework/strings_and_rspec_spec.rb b/week1/homework/strings_and_rspec_spec.rb index 2f188f6..8e18929 100644 --- a/week1/homework/strings_and_rspec_spec.rb +++ b/week1/homework/strings_and_rspec_spec.rb @@ -13,6 +13,18 @@ @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 +<<<<<<< HEAD + count = @my_string.length + count.should eq @my_string.length.size + end + it "should be able to split on the . charater" do + result = @my_string.split("\.") + result.should have(2).items + end + it "should be able to give the encoding of the string" do + encoding = @my_string.encoding + encoding.should eq (Encoding.find("UTF-8")) +======= @my_string.should have(@my_string.size).characters end it "should be able to split on the . charater" do @@ -21,6 +33,7 @@ end it "should be able to give the encoding of the string" do @my_string.encoding.should eq (Encoding.find("UTF-8")) +>>>>>>> 476e4b543ee68aad8bb809afdfe2207afd39e8e5 end end end diff --git a/week2/exercises/book.rb b/week2/exercises/book.rb index 50bc054..759ac83 100644 --- a/week2/exercises/book.rb +++ b/week2/exercises/book.rb @@ -1,13 +1,12 @@ class Book + attr_reader :title, :pages - attr_accessor :title, :pages + def initialize(title, pages) + @title = title + @pages = pages + end - def initialize(title, pages) - @title = title - @pages = pages - end - - def page_count - "Page count is #{@pages}" - end + def page_count + "Page count is #{@pages}" + end end diff --git a/week2/exercises/book_spec.rb b/week2/exercises/book_spec.rb index bb22819..f01bb91 100644 --- a/week2/exercises/book_spec.rb +++ b/week2/exercises/book_spec.rb @@ -1,5 +1,4 @@ require './book.rb' - describe Book do before :each do @book = Book.new("Harry Potter", 200) diff --git a/week2/homework/questions.txt b/week2/homework/questions.txt index 4cfc0a3..fc6e3db 100644 --- a/week2/homework/questions.txt +++ b/week2/homework/questions.txt @@ -1,18 +1,25 @@ 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? -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 can be indexed with anything whereas an Array can only be indexed by integers. 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. +I would use a Hash if I needed to make associations between two objects or create a count list. +I would use an Array if the stored information somehow relied on indexes that were consecutively ordered integers. This could be as simple as having a list of itmes that is ordered by importance. + +3. What is a module? +A module can store constants, methods, and classes. Modules can be used to share functionality without being constrained to ideas of hierarchies that comes with inheritance. + +Enumerable is a built in Ruby module, what is it? +Provided that class that includes Enumerable implements an "each" method, Enumerable allows for the same functionality of Collections. -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. 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 does not support multiple inheritance. However, since a child class can inherit from more than one thing because of the inheritance hierarchy; a child class can inherit from a parent class which in turn may have inherited from its own parent class. Additionally, modules can be used to share functionality. 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 Class can be instantiated. Modules can have contracts that may require inheriting classes to implement certain methods. + diff --git a/week2/homework/simon_says.rb b/week2/homework/simon_says.rb index fa35ccd..558bd7b 100644 --- a/week2/homework/simon_says.rb +++ b/week2/homework/simon_says.rb @@ -1,16 +1,27 @@ module SimonSays - def echo(st) - st - end - - def shout(st) - st.upcase - end - def first_word(st) - st.split.first - end + def echo(str) + str + end + + def shout(str) + str.upcase + end + + def repeat(str, n=2) + str = ((str + ' ') * n).strip + end + + def start_of_word(str, n) + str[0, n] + end + + def first_word(str) + str.split(' ').first + end +<<<<<<< HEAD +======= def start_of_word(st,i) st[0...i] end @@ -20,3 +31,4 @@ def repeat(st, t=2) ([st]*t).join(' ') end end +>>>>>>> 15e2934dd67bd9a431f1e6ce9ad8fc2e50446bbb diff --git a/week2/homework/simon_says_spec.rb b/week2/homework/simon_says_spec.rb index a17ac8d..ae3f5bb 100644 --- a/week2/homework/simon_says_spec.rb +++ b/week2/homework/simon_says_spec.rb @@ -1,4 +1,6 @@ # Hint: require needs to be able to find this file to load it +#require "./simon_says.rb" +#include 'simon_says.rb' require "./simon_says.rb" describe SimonSays do diff --git a/week3/exercises/monster.rb b/week3/exercises/monster.rb index 013c3d2..fede1a6 100644 --- a/week3/exercises/monster.rb +++ b/week3/exercises/monster.rb @@ -1,14 +1,14 @@ require './named_thing.rb' class Monster - include NamedThing - attr_accessor :vulnerabilities, :dangers - attr_reader :nocturnal, :legs + include NamedThing + attr_accessor :vulnerabilities, :dangers + attr_reader :nocturnal, :legs - def initialize(noc, legs, name="Monster", vul = [], dangers = []) - super(name) - @nocturnal = noc - @vlunerabilities = vul - @dangers = dangers - @legs = legs - end + def initialize(name="Monster", noc, vul = [], dangers = [], legs) + super(name) + @nocturnal = noc + @vulnerabilities = vul + @dangers = dangers + @legs = legs + end end diff --git a/week3/exercises/monster_exercise.rb b/week3/exercises/monster_exercise.rb new file mode 100644 index 0000000..9f6757b --- /dev/null +++ b/week3/exercises/monster_exercise.rb @@ -0,0 +1,11 @@ +require './monsters.rb' +require './monster.rb' + +#How many monsters are nocturnal? +puts $monsters.find_all{|m| m[:nocturnal]}.count + +#What are the names of the monsters that are nocturnal? + +#How many legs do all mosnters have? +#puts $monsters.find_all{|m| m[:legs]}.count + diff --git a/week3/homework/calculator.rb b/week3/homework/calculator.rb index f8916e3..cf561d9 100644 --- a/week3/homework/calculator.rb +++ b/week3/homework/calculator.rb @@ -1,4 +1,26 @@ class Calculator +<<<<<<< HEAD + def sum(num_array) + sum = num_array.inject(0) {|sum, num| sum += num } + end + + def multiply(*nums) + num_array = *nums.flatten + num_array.inject(1) {|product, num| product *= num} + end + + def pow(a, b) + a ** b + end + + def factorial(a) + if a <= 1 + a + else + a * self.factorial(a - 1) + end + end +======= def sum(array) array.inject(0){|sum, x| sum +x} end @@ -21,4 +43,5 @@ def fac(n) def pow_fac(base=nil, p) (1..p).to_a.inject(1){|f,v| f *= base || v} end +>>>>>>> 15e2934dd67bd9a431f1e6ce9ad8fc2e50446bbb end diff --git a/week3/homework/calculator_spec.rb b/week3/homework/calculator_spec.rb index 5a418ed..2776326 100644 --- a/week3/homework/calculator_spec.rb +++ b/week3/homework/calculator_spec.rb @@ -3,11 +3,11 @@ describe Calculator do before do - @calculator = Calculator.new + @calculator = Calculator.new end describe "#sum" do - it "computes the sum of an empty array" do + it "computes the sum of an empty array" do @calculator.sum([]).should == 0 end @@ -27,6 +27,19 @@ # Once the above tests pass, # write tests and code for the following: describe "#multiply" do +<<<<<<< HEAD + it "returns the value of a single number" do + @calculator.multiply(4).should == 4 + end + + it "multiplies two numbers" do + @calculator.multiply(4, 5).should == 20 + end + + it "multiplies an array of numbers" do + @calculator.multiply([1, 2, 3, 4, 5]).should == 120 + end +======= it "multiplies two numbers" do @calculator.multiply(2,2).should eq 4 end @@ -41,10 +54,19 @@ 32.times{ p *= 2 } @calculator.pow(2,32).should eq p end +>>>>>>> 15e2934dd67bd9a431f1e6ce9ad8fc2e50446bbb + it "raises one number to the power of another number" do + @calculator.pow(2, 3).should == 8 + end + end # http://en.wikipedia.org/wiki/Factorial describe "#factorial" do it "computes the factorial of 0" do +<<<<<<< HEAD + @calculator.factorial(0).should == 0 + end +======= @calculator.fac(0).should eq 1 end it "computes the factorial of 1" do @@ -64,5 +86,22 @@ end end +>>>>>>> 15e2934dd67bd9a431f1e6ce9ad8fc2e50446bbb + + 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..c5d5063 100644 --- a/week3/homework/questions.txt +++ b/week3/homework/questions.txt @@ -5,10 +5,28 @@ Please Read: - Chapter 22 The Ruby Language: basic types (symbols), variables and constants 1. What is a symbol? +<<<<<<< HEAD +"an identifier corresponding to a string of characters, often a name" + +2. What is the difference between a symbol and a string? +A symbol is identified with a preceding colon rather than quotation marks for strings. Symbols are better when you want to create a single word/name value that isn't arbitrary as opposed to a string variable that could have multiple values. + +3. What is a block and how do I call a block? +Code that is enclosed by braces or "do" and "end". It is different from a method in that it is anonymous as opposed to being named/defined. + +4. How do I pass a block to a method? +Write the block immediately after invocation of a method + +What is the method signature? +The components of a method that include the name of the method and applicable parameters; this lets you know how to call a method and helps the interpreter/compiler/parser/etc. know the difference between one method versus another. + +5. Where would you use regular expressions? +Everywhere! Particularly when trying to find text or assign text to variables. +======= A symbol is a static name or identifier. 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 string is a collection of characters whereas a string 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. 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. @@ -26,3 +44,4 @@ end 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. +>>>>>>> 15e2934dd67bd9a431f1e6ce9ad8fc2e50446bbb diff --git a/week4/homework/questions.txt b/week4/homework/questions.txt index bc1ab7c..6f5e117 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? +Using IO objects like those from class 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!" + 3. What is the Directory class and what is it used for? +The class Dir represents a file system so that you can you can modify or view +contents. + 4. What is an IO object? +An IO object is a way to handle input and output between and among programs +as well as external sources like files. + 5. What is rake and what is it used for? What is a rake task? +Rake is a tool to help automate, order, and/or group tasks needed in software +development. This could include forms of file/directory manipulation or running +various scripts. A task, then, is one of these scripts or commands that you +can define with the the tool. + diff --git a/week5/exercises/Rakefile b/week5/exercises/Rakefile index ce332af..622226d 100644 --- a/week5/exercises/Rakefile +++ b/week5/exercises/Rakefile @@ -6,5 +6,11 @@ task :make_class_dir do Dir.mkdir("class") end -task :output +task :output /(.*)$/ do |file| + f = File.new(file, "r") + puts f.gets +end + +#task :make_name_dir do + diff --git a/week7/exercises/features/step_definitions/converter.rb b/week7/exercises/features/step_definitions/converter.rb index 4cb1264..e32c996 100644 --- a/week7/exercises/features/step_definitions/converter.rb +++ b/week7/exercises/features/step_definitions/converter.rb @@ -8,10 +8,14 @@ def type=(type) end def convert - self.send("#{@type}_convertion") + self.send("#{@type}_conversion") end - def Fahrenheit_convertion - (((@value - 32.0) /5.0) * 9.0).round(1) + def Fahrenheit_conversion + ((@value - 32.0) / 1.8).round(1) + end + + def Celsius_conversion + ((@value * 1.8) + 32).round(1) end end \ No newline at end of file diff --git a/week7/exercises/features/step_definitions/puppy.rb b/week7/exercises/features/step_definitions/puppy.rb new file mode 100644 index 0000000..10980c8 --- /dev/null +++ b/week7/exercises/features/step_definitions/puppy.rb @@ -0,0 +1,13 @@ +class Puppy + attr_accessor :name, :wags, :is_out, :peeing, :hears_bell + def initialize + @wags = "the puppy is wagging its tail" + @is_out = true + @peeing = true + @hears_bell = false + end + + def is_pet + "the puppy is wagging its tail" + end +end diff --git a/week7/exercises/features/step_definitions/puppy_steps.rb b/week7/exercises/features/step_definitions/puppy_steps.rb new file mode 100644 index 0000000..5540747 --- /dev/null +++ b/week7/exercises/features/step_definitions/puppy_steps.rb @@ -0,0 +1,37 @@ +Given /^we have a puppy$/ do + @puppy = Puppy.new + @message = "the puppy is wagging its tail" +end + +And /^its name is (.*)$/ do |name| + @puppy.name=(name) +end + +When /^we pet the puppy$/ do + @being_pet = @puppy.send(:is_pet) +end + +Then /^the puppy wags its tail$/ do + @being_pet.should == @message +end + +When /^we ring the bell$/ do + @bell_response = @puppy.send(:hears_bell=, true) + @bell_response.should == true +end + +And /^it wags its tail$/ do + @wags = @puppy.send(:wags) + @wags.should == @message +end + +Then /^we must take it out$/ do + @take_out_pet = @puppy.send(:is_out) + @take_out_pet.should == true + @puppy.send(:peeing=, false) +end + +And /^then it will not pee on the floor$/ do + @peeing = @puppy.send(:peeing) + @peeing.should == false +end \ No newline at end of file diff --git a/week7/homework/features/pirate.feature b/week7/homework/features/pirate.feature index 7de1a0b..0103284 100644 --- a/week7/homework/features/pirate.feature +++ b/week7/homework/features/pirate.feature @@ -1,11 +1,20 @@ +# encoding: utf-8 # language: en-pirate Ahoy matey!: Pirate Speak - I would like help to talk like a pirate +#Feature: Pirate Speak + #I would like help to talk like a pirate Heave to: The mighty speaking pirate - Gangway! I have a PirateTranslator - Blimey! I say 'Hello Friend' - Aye I hit translate - Let go and haul it prints out 'Ahoy Matey' - Avast! it also prints 'Shiber Me Timbers You Scurvey Dogs!!' +#Scenario: The mighty speaking pirate + Gangway! I have a PirateTranslator + #Given I have a PirateTranslator + Blimey! I say 'Hello Friend' + #When I say 'Hello Friend' + Aye I hit translate + #And I hit translate + + Let go and haul it prints out 'Ahoy Matey' + #Then it prints out 'Ahoy Matey' + Avast! it also prints 'Shiber Me Timbers You Scurvey Dogs!!' + #But it also prints 'Shiber Me Timbers You Scurvey Dogs!!' diff --git a/week7/homework/features/step_definitions/PirateTranslator.rb b/week7/homework/features/step_definitions/PirateTranslator.rb new file mode 100644 index 0000000..26f5201 --- /dev/null +++ b/week7/homework/features/step_definitions/PirateTranslator.rb @@ -0,0 +1,6 @@ +class PirateTranslator + def translate(*words) + puts "Ahoy Matey!" + puts 'Shiber Me Timbers You Scurvey Dogs!!' + end +end \ No newline at end of file diff --git a/week7/homework/features/step_definitions/TicTacToe.rb b/week7/homework/features/step_definitions/TicTacToe.rb new file mode 100644 index 0000000..92997a7 --- /dev/null +++ b/week7/homework/features/step_definitions/TicTacToe.rb @@ -0,0 +1,114 @@ +class TicTacToe + attr_accessor :board, :draw + attr_reader :player, :player_symbol, :player_won + attr_reader :computer_symbol + attr_reader :current_player, :open_spots, :over + attr_writer :computer_move + SYMBOLS = [:X, :O] + + def initialize(p=:Renee, sym=SYMBOLS.sample) + @player = @current_player = p.to_s.capitalize + @player_symbol = sym + if @player_symbol == :X + @computer_symbol = :O + else + @computer_symbol = :X + end + + @open_spots = [:A1, :A2, :A3, :B1, :B2, :B3, :C1, :C2, :C3] + @board = { :A1 => ' ', :A2 => ' ', :A3 => ' ', + :B1 => ' ', :B2 => ' ', :B3 => ' ', + :C1 => ' ', :C2 => ' ', :C3 => ' ' } + @player_move = nil + @over = false + end + def method_missing(method, *args, &block) + if method.to_s.end_with? '?' + self.send(method.to_s.chomp.gsub('?', '').to_sym, *args, &block) + else + super + end + end + def current_state + @board.values + end + def spots_open? + @board.include?(' ') + end + def player=(p) + @player = p.to_s.capitalize + @current_player = @player #if @player_turn + end + def determine_winner + letters = ['A', 'B', 'C'] + nums = [1, 2, 3] + win = nil + + letters.each do |letter| + if @board[(letter+'1').to_sym] == @board[(letter+'2').to_sym] && @board[(letter+'2').to_sym] == @board[(letter+'3').to_sym] + win = @board[letter+'1'] + end + end + + if win == nil + nums.each do |num| + num = num.to_s + if @board[('A'+num).to_sym] == @board[('B'+num).to_sym] && @board[('B'+num).to_sym] == @board[('C'+num).to_sym] + win = @board[('A'+num).to_sym] + end + end + end + + if win == nil + if @board[:A1] == @board[:B2] && @board[:B2] == @board[:C3] + win = @board[:A1] + elsif @board[:A3] == @board[:B2] && @board[:B2] == @board[:C1] + win = @board[:A3] + else + @draw = true + end + end + + if @player_symbol == win + @player_won = true + end + + @over = true if win || @draw + end + def computer_move + @current_player = @player + temp = @open_spots.sample + @board[temp] = @computer_symbol.to_s + @open_spots -= [@temp] + temp + end + def player_turn#### + @current_player == @player + end + def get_player_move + @player_move = gets.chomp + until @open_spots.include?(@player_move.to_sym) + @player_move = gets.chomp + end + end + def player_move + @current_player = 'Computer' + + if @player_move == nil + @player_move = self.get_player_move + end + if @board[@player_move.to_sym] != ' ' + @player_move = self.get_player_move + end + + @open_spots -= [@player_move.to_sym] + @board[@player_move.to_sym] = @player_symbol.to_s + @player_move = @player_move.to_sym + end + def welcome_player + "Welcome #{@player}" + end + def indicate_player_turn + @player_turn######### + end +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..018829f 100644 --- a/week7/homework/features/step_definitions/pirate_steps.rb +++ b/week7/homework/features/step_definitions/pirate_steps.rb @@ -1,19 +1,24 @@ -Gangway /^I have a (\w+)$/ do |arg| - @translator = Kernel.const_get(arg).new -end +#encoding: utf-8 + +require "rspec/mocks/standalone" -Blimey /^I (\w+) '(.+)'$/ do |method, arg| - @translator.send(method, arg) +Given /^I have a PirateTranslator$/ do + @translator = PirateTranslator.new end -Letgoandhaul /^I hit (\w+)$/ do |arg| - @result = @translator.send(arg) +When /^I say ('Hello Friend')$/ do |words| + @words_said = words end -Letgoandhaul /^it prints out '(.+)'$/ do |arg| - @result.split("\n ").first.should == arg +#reminder: Then is interchangeable with And +Then /^I hit translate$/ do + @translated = @translator.translate(@words_said) end -Letgoandhaul /^it also prints '(.+)'$/ do |arg| - @result.split("\n ").last.should == arg +Then /^it prints out (.*)$/ do |arg1| + @translator.should_receive(:puts).with(arg1) end + +Then /^it also prints (.*)$/ do |arg2| + @translator.should_receive(:puts).with(arg2) +end \ No newline at end of file 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..c671381 100644 --- a/week7/homework/features/step_definitions/tic-tac-toe-steps.rb +++ b/week7/homework/features/step_definitions/tic-tac-toe-steps.rb @@ -1,3 +1,4 @@ +#encoding: utf-8 require 'rspec/mocks/standalone' Given /^I start a new Tic\-Tac\-Toe game$/ do @@ -35,7 +36,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/tic-tac-toe.feature b/week7/homework/features/tic-tac-toe.feature index 6f3134d..52f82b3 100644 --- a/week7/homework/features/tic-tac-toe.feature +++ b/week7/homework/features/tic-tac-toe.feature @@ -1,3 +1,4 @@ +# encoding: utf-8 Feature: Tic-Tac-Toe Game As a game player I like tic-tac-toe In order to up my skills @@ -54,4 +55,4 @@ Scenario: Game is a draw And there are not three symbols in a row When there are no open spaces left on the board Then the game is declared a draw - And the game ends + And the game ends \ No newline at end of file diff --git a/week7/homework/play_game.rb b/week7/homework/play_game.rb index cf7847f..41a7eb1 100644 --- a/week7/homework/play_game.rb +++ b/week7/homework/play_game.rb @@ -1,5 +1,5 @@ -require './features/step_definitions/tic-tac-toe.rb' - +#require './features/step_definitions/tic-tac-toe.rb' +require './features/step_definitions/TicTacToe.rb' @game = TicTacToe.new puts @game.welcome_player @@ -8,7 +8,7 @@ when "Computer" @game.computer_move when @game.player - @game.indicate_palyer_turn + @game.indicate_player_turn @game.player_move end puts @game.current_state diff --git a/week7/homework/questions.txt b/week7/homework/questions.txt index d55387d..770f3b8 100644 --- a/week7/homework/questions.txt +++ b/week7/homework/questions.txt @@ -1,9 +1,41 @@ - 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? -4. What is the difference between a class method and an instance method? What is the difference between instance_eval and class_eval? +method_missing is a way to reuse functionality/code in order to define methods +on the fly. For example, if I created a method called discipline_rabbit and wanted +to increase readability and enable usage of a similar method that works with +multiple rabbits, I could define in method_missing a way to automatically +understand discipline_rabbits or discipline_cats and resue functionality from +the original discipline_dog method. + +2. What is and Eigenclass and what is it used for? +An Eigenclass, or a Singleton class, is a way to define functionality for a +specific object or instance of a class. Practically, I'm not really sure why +I'd use it. I suppose I'd use it to create specific functionalilty without +bothering with making a more complicated inheritance hierarchy. + +Where Do Singleton methods live? +In the class object + + +3. When would you use DuckTyping? How would you use it to improve your code? +Probably always from now on because it sounds more fun than static typing. +Specifically, it seems that it would make it easier for me to think about my +methods and method usage based on what I know (or think) the arguments can +respond to instead of its defined type. + + +4. What is the difference between a class method and an instance method? +Class methods are called from the class; instance methods are called from an +instance of its class. + +What is the difference between instance_eval and class_eval? +Basically, class_eval creates instance methods for a class; instance_eval creates class methods for an EigenClass of the class. + 5. What is the difference between a singleton class and a singleton method? +When defining singleton methods, singleton classes are automatically created +to store the singleton method. This contrats normal methods which must be +defined within a class first if it is to be either a class or instance method +(except for various metaprogramming methods). + diff --git a/week8/exercises/couch.rb b/week8/exercises/couch.rb index a52eb35..204389a 100644 --- a/week8/exercises/couch.rb +++ b/week8/exercises/couch.rb @@ -4,17 +4,23 @@ def initialize(pillows, cushions) @cushions = cushions end - def pillow_colors - @pillows.join(", ") - end - - def cushion_colors - @cushions.join(", ") - end - [:pillows, :cushions].each do |s| define_method("how_many_#{s}") do instance_variable_get("@#{s}").count end + define_method("#{s}_colors") do + instance_variable_get("@#{s}").join(' ') + end + end + + def to_str + "i am a couch" + end + def method_missing(meth, *args, &block) + puts "You called #{meth} with #{args.join(' ')}" + define_method(meth) do + puts "hello world" + end + super end -end +end \ No newline at end of file