Skip to content
This repository was archived by the owner on Dec 1, 2021. It is now read-only.

Complete final #174

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions week1/homework/questions.txt
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
Please read:
Chapter 3 Classes, Objects, and Variables
Please read:
Chapter 3 Classes, Objects, and Variables
p.90-94 Strings

1. What is an object?
An object is a representation in memory of a specific concept or thing that the Ruby interpreter knows about.
Everything that you can manipulate in Ruby is an object and every object in Ruby was generated directly or indirectly from a class. [Thomas p.29]
Therefore, all variables reference objects. An object typically holds some type of data or state. Each object in Ruby has a unique identifier.

2. What is a variable?
A variable is a name for a location in memory. It can contain, or point to, any type of object.
A name used to reference a value or an allocated space for a value.
Variables are used to keep track of objects: each variable holds a reference to an object. [Thomas p.43]
A variable is simply a reference to an object. [Thomas p.43]

3. What is the difference between an object and a class?
An object is an instance of a class, or a specific thing of that class's type in memory. The class is the specifics that are common to all things of that type. The classification of a concept or a thing is a class. A specific thing or concept of a class's type in memory is an object. For example: All books have titles (Class). This book's title is "Harry Potter and the Goblet of Fire" (Object).
Everything that you can manipulate in Ruby is an object. [Thomas p.29]
A class is an object that can be used to instantiate a number of objects with similar attributes, while each being independent (having different identities) of the other objects instantiated with the class.

4. What is a String?
A string is how Ruby understands text. It is a collection of characters (Bytes), and can be created by making an instance of the String class (String.new) or as a string literal ("",'', %Q[]).
Ruby strings are simply sequences of characters. They normally hold printable characters but that is not a requirement; a string can also hold binary data. Strings are objects of class String. [Thomas p.90]

5. What are three messages that I can send to a string object? Hint: think methods
chomp! - removes newline characters, or the specified characters, from the end of a string
strip! - removes leading or trailing whitespace from a string
split - returns an array of strings made up of the original string separated on whitespace or the specified characters or regexp
squeeze
split
chomp

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.

Strings can be defined via single quotes, double quotes, %q, %Q, or with a here document.
Strings defined with double quotes can escape backslashes and single quotes while double quoted strings support many more escape sequences.
34 changes: 17 additions & 17 deletions week1/homework/strings_and_rspec_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,24 @@
# Please make these examples all pass
# You will need to change the 3 pending tests
# You will need to write a passing test for the first example
# (Hint: If you need help refer to the in-class exercises)
# (Hint: If you need help refer to the in-class exercises)
# The two tests with the pending keyword, require some ruby code to be written
# (Hint: You should do the reading on Strings first)
# (Hint: You should do the reading on Strings first)

describe String do
context "When a string is defined" do
before(:all) do
@my_string = "Renée is a fun teacher. Ruby is a really cool programming language"
end
it "should be able to count the charaters" do
@my_string.should have(@my_string.size).characters
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
@my_string.encoding.should eq (Encoding.find("UTF-8"))
end
end
context "When a string is defined" do
before(:all) do
@my_string = "Renée is a fun teacher. Ruby is a really cool programming language"
end
it "should be able to count the characters" do
@my_string.length.should eq 66
end
it "should be able to split on the . character" do
result = @my_string.split('.')
result.should have(2).items
end
it "should be able to give the encoding of the string" do
@my_string.encoding.should eq (Encoding.find("UTF-8"))
end
end
end
14 changes: 7 additions & 7 deletions week2/homework/questions.txt
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
Please Read The Chapters on:
Containers, Blocks, and Iterators
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.
The class Array holds a collection of object references. Each object reference occupies a position in the array, identified by a non-negative integer index. [Thomas p47] Hashes are similar to arrays in that they are indexed collections of object references. However, although you index arrays with integers, you can index a hash with objects of any type. [Thomas p50]

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.
Use a hash when you would like to use any object as an index (key). Use an array when you don't need or don't want to have to index values by a custom key. As of Ruby 1.9, hashes remember the order in which you add items to the hash, like arrays do innately.

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.
Enumerable is a module that defines useful iterator methods (methods that invoke a block of code) that can be included by classes that define collections such as the Array class.

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.
Because Ruby has single inheritance for classes, if you need to inherit functionality from more than one class, you might instead consider breaking that functionality into multiple modules which can then be included.

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.
Classes and modules both define methods. A class can hold state using self and provide behavior using methods that may or may not act on self. If the ability to hold state is not needed, a module could instead be used, which only provides behavior via methods and does not provide a mechanism for keeping state.
46 changes: 28 additions & 18 deletions week2/homework/simon_says.rb
Original file line number Diff line number Diff line change
@@ -1,22 +1,32 @@
module SimonSays
def echo(st)
st
end

def shout(st)
st.upcase
end

def first_word(st)
st.split.first
end
# Returns the given str.
def echo(str)
str
end

def start_of_word(st,i)
st[0...i]
end

def repeat(st, t=2)
return "Go Away!" if t==0
([st]*t).join(' ')
end
# Returns a copy of str with all lowercase letters replaced with their uppercase counterparts.
def shout(str)
str.upcase
end

# Returns a copy of str, repeated count times and separated with a single space.
def repeat(str, count = 2)
raise ArgumentError, "count must be a positive integer" if !(count.is_a? Integer) || count < 1

(1..count).collect{ str }.join(' ')
end

# Returns the portion of word from the beginning of word to the given length.
def start_of_word(word, length)
raise ArgumentError, "length must be an integer greater or equal to 0" if !(length.is_a? Integer) || length < 0
raise ArgumentError, "length is greater than the length of word" if length > word.length

word[0, length]
end

# Returns a new string of the first word in str.
def first_word(str)
str.split(' ')[0]
end
end
2 changes: 1 addition & 1 deletion week3/class_materials/resources.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ Array: http://www.ruby-doc.org/core-1.9.3/Array.html
Hash: http://www.ruby-doc.org/core-1.9.3/Hash.html
Range: http://ruby-doc.org/core-1.9.3/Range.html

Why's Poignant Guide: http://mislav.uniqpath.com/poignant-guide/
Why's Poignant Guide: http://mislav.uniqpath.com/poignant-guide/
69 changes: 47 additions & 22 deletions week3/homework/calculator.rb
Original file line number Diff line number Diff line change
@@ -1,24 +1,49 @@
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)
#(1...p).to_a.inject(base){|r,v| r *= base}
pow_fac(base, p)
end

def fac(n)
#(1..n).to_a.inject(1){|f,v| f *= v}
pow_fac(n)
end
private
def pow_fac(base=nil, p)
(1..p).to_a.inject(1){|f,v| f *= base || v}
end

# Initializes the calculator.
def initialize
end

# Returns the sum of the given numbers or an array of numbers.
def sum(*arr)
arr.flatten!

arr.each{ |n| raise ArgumentError, "arguments must be of type Number or an
Array of variables all of type Numeric" unless n.is_a? Numeric }

if arr.length > 0
arr.inject(:+)
else
0
end
end

# Returns the product of the given numbers or an array of numbers.
def product(*arr)
arr.flatten!

arr.each{ |n| raise ArgumentError, "arguments must be of type Numeric or an
Array of variables all of type Numeric" unless n.is_a? Numeric }

arr.inject(:+)
end

# Returns the result of the base number raised to the power of the exponent number.
def pow(base, exponent)
raise ArgumentError, "base must be of type Numeric" unless base.is_a? Numeric
raise ArgumentError, "exponent must be of type Numeric" unless exponent.is_a? Numeric

base ** exponent
end

# Returns the factorial of the specified number.
def factorial(num)
raise ArgumentError, "argument must be a non-negative integer" if !(num.is_a? Integer) || num < 0

if num == 0
1
else
num * factorial(num - 1)
end
end
end
54 changes: 23 additions & 31 deletions week3/homework/calculator_spec.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
require "#{File.dirname(__FILE__)}/calculator"

describe Calculator do

before do
@calculator = Calculator.new
end
Expand All @@ -10,59 +10,51 @@
it "computes the sum of an empty array" do
@calculator.sum([]).should == 0
end

it "computes the sum of an array of one number" do
@calculator.sum([7]).should == 7
end

it "computes the sum of an array of two numbers" do
@calculator.sum([7,11]).should == 18
end

it "computes the sum of an array of many numbers" do
@calculator.sum([1,3,5,7,9]).should == 25
end
end

# Once the above tests pass,
# write tests and code for the following:
describe "#multiply" do
it "multiplies two numbers" do
@calculator.multiply(2,2).should eq 4
end

it "multiplies an array of numbers" do
@calculator.multiply([2,2]).should eq 4
end
describe "#product" do
it "multiplies two numbers" do
@calculator.product(2, 3) == 6
end

it "multiplies an array of numbers" do
@calculator.product([2, 3, 4]) == 24
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
@calculator.pow(2, 4) == 32
end
end

# http://en.wikipedia.org/wiki/Factorial

describe "#factorial" do
it "computes the factorial of 0" do
@calculator.fac(0).should eq 1
@calculator.factorial(0) == 1
end
it "computes the factorial of 1" do
@calculator.fac(1).should eq 1
@calculator.factorial(1) == 1
end

it "computes the factorial of 2" do
@calculator.fac(2).should eq 2
@calculator.factorial(2) == 2
end

it "computes the factorial of 5" do
@calculator.fac(5).should eq 120
@calculator.factorial(5) == 120
end

it "computes the factorial of 10" do
@calculator.fac(10).should eq 3628800
@calculator.factorial(10) == 3628800
end

end

end
24 changes: 15 additions & 9 deletions week3/homework/questions.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,30 @@ Please Read:
- Chapter 22 The Ruby Language: basic types (symbols), variables and constants

1. What is a symbol?
A symbol is a static name or identifier.
Symbols are "scalar value objects used as identifiers, mapping immutable strings to fixed internal values." [Peter Cooper, Ruby Reloaded]

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.
Symbols are immutable objects and if having the same name are the same object in memory while strings are mutable objects which have their own place in memory and can be manipulated by methods in the String class.

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.
A block is simply a chunk of code enclosed in either braces or the keywords do and end. [Thomas p.55] Blocks are like anonymous methods. [Thomas p.66] Alternatively, blocks can be converted into an object having closure. You call a block using one of the ways outlined in the next answer.

4. How do I pass a block to a method? What is the method signature?
To pass a block to a method you define the block after the method call with either the curly bracket enclosure {} or the do/end syntax. An example of passing a block to the each method of an array:
You pass a block to a method in two ways:

my_array.each {|a| puts a}
Oneline:
my_receiver.my_method(args) { |v| v }

Any method in Ruby can take a block. You can explicitly add a block to a method by putting an ampersand & before the variable name in the method definition. An example of this would be:
Multiline:
my_receiver.my_method(args) do |v|
v
end

You could then write the method signature like this that would act upon the block variables and return the output using the yield keyword:

def my_method(&my_block)
my_block.call
def my_method
yield(v + 1)
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.
One might use regular expressions to test a string to see whether it mathces a pattern, extract sections of a string that match all or part of a pattern, or change a string, replacing parts that match a pattern. [Thomas p.99]
Loading