diff --git a/Untitled Folder/tictactoe b/Untitled Folder/tictactoe new file mode 160000 index 0000000..43d6d85 --- /dev/null +++ b/Untitled Folder/tictactoe @@ -0,0 +1 @@ +Subproject commit 43d6d855b7aba545e55d39122177e64c42a02956 diff --git a/backup/tictactoe b/backup/tictactoe new file mode 160000 index 0000000..43d6d85 --- /dev/null +++ b/backup/tictactoe @@ -0,0 +1 @@ +Subproject commit 43d6d855b7aba545e55d39122177e64c42a02956 diff --git a/example_gems/prevet_mir/lib/prevet_mir.rb b/example_gems/prevet_mir/lib/prevet_mir.rb new file mode 100644 index 0000000..088b460 --- /dev/null +++ b/example_gems/prevet_mir/lib/prevet_mir.rb @@ -0,0 +1,5 @@ +class PrevetMir + def self.hi + puts "Prevet, mir!" + end +end \ No newline at end of file diff --git a/example_gems/prevet_mir/prevet_mir-0.0.0.gem b/example_gems/prevet_mir/prevet_mir-0.0.0.gem new file mode 100644 index 0000000..5fd9ddd Binary files /dev/null and b/example_gems/prevet_mir/prevet_mir-0.0.0.gem differ diff --git a/example_gems/prevet_mir/prevet_mir.gemspec b/example_gems/prevet_mir/prevet_mir.gemspec new file mode 100644 index 0000000..4e69b0e --- /dev/null +++ b/example_gems/prevet_mir/prevet_mir.gemspec @@ -0,0 +1,11 @@ +Gem::Specification.new do |s| + s.name = 'prevet_mir' + s.version = '0.0.0' + s.date = '2013-11-19' + s.summary = "Making a test gem" + s.description = "This gem was the first gem made by man. No gem has so far matched it for gemliness. Test_gem is a hundred dollars in your pocket right away. Don't turn your back on test_gem; it's trying to give you an ice cream cone and you'll get ice cream on your back." + s.authors = ["Rob Whitehead"] + s.email = 'rob.whitehead@gmail.com' + s.files = ["lib/prevet_mir.rb"] + s.homepage = 'https://rubygems.org/gems/prevet_mir' +end \ No newline at end of file diff --git a/example_gems/test_gem/bin/test_gem b/example_gems/test_gem/bin/test_gem new file mode 100644 index 0000000..7bb9d23 --- /dev/null +++ b/example_gems/test_gem/bin/test_gem @@ -0,0 +1,9 @@ +#!/usr/bin/env ruby + +require 'test_gem' + +h = HelloWorld.new + +h.test + +h.test_args ARGV.first \ No newline at end of file diff --git a/example_gems/test_gem/lib/test_gem.rb b/example_gems/test_gem/lib/test_gem.rb new file mode 100644 index 0000000..7451266 --- /dev/null +++ b/example_gems/test_gem/lib/test_gem.rb @@ -0,0 +1,2 @@ +puts "GEM GEM GEM GET OVER HERE AND GET DOWN WITH YOUR OWN BAD SELVES FLY YO FREAK FLAGS" + diff --git a/example_gems/test_gem/test_gem.gemspec b/example_gems/test_gem/test_gem.gemspec new file mode 100644 index 0000000..25e085a --- /dev/null +++ b/example_gems/test_gem/test_gem.gemspec @@ -0,0 +1,12 @@ +Gem::Specification.new do |s| + s.name = 'test_gem_chiteri' + s.version = '0.0.0' + s.date = '2013-11-12' + s.summary = "Making a test gem" + s.description = "This gem was the first gem made by man. No gem has so far matched it for gemliness. Test_gem is a hundred dollars in your pocket right away. Don't turn your back on test_gem; it's trying to give you an ice cream cone and you'll get ice cream on your back." + s.authors = ["Rob Whitehead"] + s.email = 'rob.whitehead@gmail.com' + s.files = ["lib/test_gem.rb"] + s.homepage = 'https://rubygems.org/gems/test_gem' + s.executables << 'test_gem' +end \ No newline at end of file diff --git a/midterm/even_number.rb b/midterm/even_number.rb new file mode 100644 index 0000000..8926caa --- /dev/null +++ b/midterm/even_number.rb @@ -0,0 +1,38 @@ +class EvenNumber + include Enumerable + attr_reader :input + def initialize *input + @input = input + check = true + @input.each do |i| + if i.odd? + check = false + end + end + if not check + @input = "even numbers only buddy" + end + @current = -1 + end + + def compare a, b + if @input.is_a?(Array) + output = false + if @input[a] == @input[b] + output = true + end + output + end + end + + def range a,b + r = @input[a]..@input[b] + out = r.step(2).to_a + out + end + + def next + @current += 1 + @input[@current] + end +end \ No newline at end of file diff --git a/midterm/even_number_spec.rb b/midterm/even_number_spec.rb new file mode 100644 index 0000000..3a90270 --- /dev/null +++ b/midterm/even_number_spec.rb @@ -0,0 +1,37 @@ + #- 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 "#{File.dirname(__FILE__)}/even_number.rb" + + +describe EvenNumber do + it "should only allow even numbers" do + a = EvenNumber.new(3, 4, 5) + a.input.should == "even numbers only buddy" + end + + it "should be able to get the next even number" do + a = EvenNumber.new(2, 4, 6, 8) + a.next.should eq 2 + a.next.should eq 4 + a.next.should eq 6 + a.next.should eq 8 + end + + it "should compare even numbers" do + a = EvenNumber.new(2, 4) + a.compare(0,1).should be false + b = EvenNumber.new(2,2) + b.compare(0,1).should be true + end + + it "should generate a range of even numbers" do + a = EvenNumber.new(2,8) + a = a.range(0,1) + a.should eq [2,4,6,8] + end +end \ No newline at end of file diff --git a/midterm/instructions_and_questions.txt b/midterm/instructions_and_questions.txt index 177358a..fcbbda3 100644 --- a/midterm/instructions_and_questions.txt +++ b/midterm/instructions_and_questions.txt @@ -11,15 +11,37 @@ Instructions for Mid-Term submission and Git Review (10pts): Questions (20pts): - What are the three uses of the curly brackets {} in Ruby? + Curly braces in Ruby are used for delimiting blocks (by convention, single line blocks--multiline blocks are typically done with do/end), string interpolation (e.g. "hello #{world}", where world is a variable or expression), and defining hashes. + - What is a regular expression and what is a common use for them? + Regular expressions are a set of symbols used to search out specific patterns of text. A regular expression might be used to verify that input is shaped like an email address, or pick out any capitalized words in a sentence. + - What is the difference between how a String, a symbol, a FixNum, and a Float are stored in Ruby? + Strings are stored as literal objects, each instance of which is unique. If an identical string is assigned twice, i.e. a = "hello", b = "hello", there will be two objects with different memory addresses. + + In contrast, any symbol with an identical name is assigned to the same memory address. + + There is a similar distinction between FixNums and Floats--FixNums of the same value have the same memory address, and floats of the same value do not. + - Are these two statements equivalent? Why or Why Not? 1. x, y = "hello", "hello" 2. x = y = "hello" + + The two statements are not equivalent. #1 saves them as two different objects. If x is altered, for example if x.chop! is called, removing the last character, y will be unaffected. + In #2, both variables point to the same object. If x.chop! is called, y will also be affected--it points to the same string that just got chopped. + + - What is the difference between a Range and an Array? +Ranges define a set of numbers in a certain order incrementing in a certain way. Their specific values are calculated at run-time. Until then they are stored as a Range object. An array can contain objects in any order and can be changed at any time. Arrays can contain any kind of object as elements, but the objects that define a range must respond to the 'succ' method to define the next object in succession. + - Why would I use a Hash instead of an Array? +Hashes are more versatile in use--instead of keeping track of the order of the array and make sure it's not disrupted as you move things around, you can simply assign keys and Ruby will keep it straight. On the other hand, hashes are much more expensive, processor-wise. + - What is your favorite thing about Ruby so far? +Its forgiveness--I find myself using a lot of Python syntax by mistake (for example, I put method arguments in parens) and Ruby usually doesn't care. + - What is your least favorite thing about Ruby so far? +When something in Ruby is opaque, it is REALLY opaque. The syntax allows for very elegant code, but it can be difficult to understand what is going on. Programming Problems (10pts each): - Write a passing rspec file called even_number_spec.rb that tests a class called EvenNumber. diff --git a/midterm/mid_term_spec.rb b/midterm/mid_term_spec.rb index 0556a97..e6f77dc 100644 --- a/midterm/mid_term_spec.rb +++ b/midterm/mid_term_spec.rb @@ -1,4 +1,4 @@ -require "#{File.dirname(__FILE__)}/turkey" +require "#{File.dirname(__FILE__)}/turkey.rb" describe Turkey do @@ -20,7 +20,7 @@ end -require "#{File.dirname(__FILE__)}/thanksgiving_dinner" +require "#{File.dirname(__FILE__)}/thanksgiving_dinner.rb" describe ThanksgivingDinner do diff --git a/midterm/thanksgiving_dinner.rb b/midterm/thanksgiving_dinner.rb new file mode 100644 index 0000000..8a5e563 --- /dev/null +++ b/midterm/thanksgiving_dinner.rb @@ -0,0 +1,93 @@ +=begin + responds to: guests, menu, diet, proteins (array w/strings), veggies(array w/symbols and strings), dessert (hash) + kind of: Dinner + takes parameter: :diet + method: seating_chart_size (inject) + whats_for_dinner + whats_for_dessert +=end +class Dinner +end + +class ThanksgivingDinner < Dinner + attr_accessor :diet, :guests, :menu, :proteins, :veggies, :desserts + def initialize diet + @diet = diet + @guests = [] + @menu = {diet: @diet} + if @menu[:diet] == :vegan + @menu = { diet: :vegan, proteins: ["Tofurkey", "Hummus"], + veggies: [:ginger_carrots , :potatoes, :yams], + desserts: {:pies => [:pumkin_pie], :other => ["Chocolate Moose"], :molds => [:cranberry, :mango, :cherry]}} + end + end + + def seating_chart_size + @guests.inject(0) {|sum, element| sum + element.length} + end + + def guests + @guests + end + + def whats_for_dinner + "Tonight we have proteins #{things_lister(@menu[:proteins])}, and veggies #{things_lister(@menu[:veggies])}." + end + + def whats_for_dessert + "Tonight we have #{dessert_counter(@menu[:desserts])} delicious desserts: #{things_lister(@menu[:desserts][:pies])}, #{things_lister(@menu[:desserts][:other])}, and #{@menu[:desserts][:molds].length} molds: #{things_lister(@menu[:desserts][:molds], true)}." + end + + def things_lister input, molds = false + d = list_preparer(input) + if d.length == 1 + output = d[0] + elsif d.length == 2 + output = d[0] + " and " + d[1] + else + count = 0 + output = "" + if not molds + d.each do |i| + if count < d.length-1 + output += (i + ", ") + count += 1 + else + output += ("and " + i) + end + end + + else + d.each do |i| + if count < d.length-1 + output += (i + " and ") + count += 1 + else + output += i + end + end + end + end + + output + end + + def list_preparer input + d = input.flatten(-1).map! do |i| #turn the input into a flat array of words + i.to_s.capitalize + end + d.delete_if {|x| x == "Pies" or x == "Other" or x == "Molds"} + d.each do |i| + pos = /[_ ]/ =~ i + if pos + i[pos] = " " + i[pos+1] = i[pos+1].capitalize + end + d + end + end + + def dessert_counter input + input[:pies].length + input[:other].length + input[:molds].length + end +end \ No newline at end of file diff --git a/midterm/turkey.rb b/midterm/turkey.rb new file mode 100644 index 0000000..cefe2e2 --- /dev/null +++ b/midterm/turkey.rb @@ -0,0 +1,45 @@ +=begin + attributes: weight + responds to: gobble_speak + inherits from: Animal +=end +class Animal +end + +class Turkey < Animal + attr_reader :weight + def initialize weight + @weight = weight + end + + def gobble_speak input + text = input.split + out = text.map do |i| + gobble_maker(i) + end + out.join(" ") + end + + def gobble_maker word + cap = false + out = "gobble" + punct = "" + if word[0] =~ /[A-Z]/ #check if word is capitalized and match the case + out = out.capitalize + end + while word[-1] =~ /[;:.,!?'"]/ #find and grab all punctuation marks from end of word + punct += word[-1] + word.chop! + end + punct.reverse! + apost = word=~/'/ #finds the apostrophe and inserts it proportionally where it should go in "gobble", rounding down to discourage end-of-word apostrophe placement + if apost + apost = ((Float(apost+1) / word.length) * 6) - 0.5 + out.insert(apost.round, "'") + end + out + punct #put it all together + + end + + +end diff --git a/midterm/wish_list.rb b/midterm/wish_list.rb new file mode 100644 index 0000000..ef4d59c --- /dev/null +++ b/midterm/wish_list.rb @@ -0,0 +1,18 @@ +#- 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 +class WishList + attr_accessor :wishes + include Enumerable + def initialize + @wishes = [] + end + + def each + @wishes.each_index do |i| + yield "#{i+1}. #{@wishes[i]}" + end + end +end + diff --git a/midterm/wish_list_spec.rb b/midterm/wish_list_spec.rb index 1ae634a..c09bdef 100644 --- a/midterm/wish_list_spec.rb +++ b/midterm/wish_list_spec.rb @@ -1,4 +1,4 @@ -require "#{File.dirname(__FILE__)}/wish_list" +require "#{File.dirname(__FILE__)}/wish_list.rb" describe WishList do before :each do diff --git a/tic-tac-toe/features/step_definitions/tic-tac-toe-steps.rb b/tic-tac-toe/features/step_definitions/tic-tac-toe-steps.rb new file mode 100644 index 0000000..a3287c1 --- /dev/null +++ b/tic-tac-toe/features/step_definitions/tic-tac-toe-steps.rb @@ -0,0 +1,124 @@ +require 'rspec/mocks/standalone' +require 'rspec/expectations' +Given /^I start a new Tic\-Tac\-Toe game$/ do + @game = TicTacToe.new +end + +When /^I enter my name (\w+)$/ do |name| + @game.player = name +end + +Then /^the computer welcomes me to the game with "(.*?)"$/ do |arg1| + @game.welcome_player.should eq arg1 +end + +Then /^randomly chooses who goes first$/ do + [@game.player, "Computer"].should include @game.current_player +end + +Then /^who is X and who is O$/ do + TicTacToe::SYMBOLS.should include @game.player_symbol, @game.computer_symbol +end + +Given /^I have a started Tic\-Tac\-Toe game$/ do + @game = TicTacToe.new(:player) + @game.player = "Renee" +end + +Given /^it is my turn$/ do + @game.current_player.should eq "Renee" +end + +Given /^the computer knows my name is Renee$/ do + @game.player.should eq "Renee" +end + +Then /^the computer prints "(.*?)"$/ do |arg1| + @game.should_receive(:puts).with(arg1) + @game.indicate_palyer_turn +end + +Then /^waits for my input of "(.*?)"$/ do |arg1| + @game.should_receive(:gets).and_return(arg1) + @game.get_player_move +end + +Given /^it is the computer's turn$/ do + @game = TicTacToe.new(:computer, :O) + @game.current_player.should eq "Computer" +end + +Then /^the computer randomly chooses an open position for its move$/ do + open_spots = @game.open_spots + @com_move = @game.computer_move + open_spots.should include(@com_move) +end + +Given /^the computer is playing X$/ do + @game.computer_symbol.should eq :X +end + +Then /^the board should have an X on it$/ do + @game.current_state.should include 'X' +end + +Given /^I am playing X$/ do + @game = TicTacToe.new(:computer, :X) + @game.player_symbol.should eq :X +end + +When /^I enter a position "(.*?)" on the board$/ do |arg1| + @old_pos = @game.board[arg1.to_sym] + @game.should_receive(:get_player_move).and_return(arg1) + @game.player_move.should eq arg1.to_sym +end + +When /^"(.*?)" is not taken$/ do |arg1| + @old_pos.should eq " " +end + +Then /^it is now the computer's turn$/ do + @game.current_player.should eq "Computer" +end + +When /^there are three X's in a row$/ do + @game = TicTacToe.new(:computer, :X) + @game.board[:C1] = @game.board[:B2] = @game.board[:A3] = :X +end + +Then /^I am declared the winner$/ do + @game.determine_winner + @game.player_won?.should be_true +end + +Then /^the game ends$/ do + @game.over?.should be_true +end + +Given /^there are not three symbols in a row$/ do + @game.board = { + :A1 => :X, :A2 => :O, :A3 => :X, + :B1 => :X, :B2 => :O, :B3 => :X, + :C1 => :O, :C2 => :X, :C3 => :O + } + @game.determine_winner +end + +When /^there are no open spaces left on the board$/ do + @game.spots_open?.should be_false +end + +Then /^the game is declared a draw$/ do + @game.draw?.should be_true +end + +When /^"(.*?)" is taken$/ do |arg1| + @game.board[arg1.to_sym] = :O + @taken_spot = arg1.to_sym +end + +Then /^computer should ask me for another position "(.*?)"$/ do |arg1| + @game.board[arg1.to_sym] = ' ' + @game.should_receive(:get_player_move).twice.and_return(@taken_spot, arg1) + @game.player_move.should eq arg1.to_sym +end diff --git a/tic-tac-toe/features/tic-tac-toe.feature b/tic-tac-toe/features/tic-tac-toe.feature new file mode 100644 index 0000000..6f3134d --- /dev/null +++ b/tic-tac-toe/features/tic-tac-toe.feature @@ -0,0 +1,57 @@ +Feature: Tic-Tac-Toe Game + As a game player I like tic-tac-toe + In order to up my skills + I would like to play agaist the computer + +Scenario: Begin Game + Given I start a new Tic-Tac-Toe game + When I enter my name Renee + Then the computer welcomes me to the game with "Welcome Renee" + And randomly chooses who goes first + And who is X and who is O + +Scenario: My Turn + Given I have a started Tic-Tac-Toe game + And it is my turn + And the computer knows my name is Renee + Then the computer prints "Renee's Move:" + And waits for my input of "B2" + +Scenario: Computer's Turn + Given I have a started Tic-Tac-Toe game + And it is the computer's turn + And the computer is playing X + Then the computer randomly chooses an open position for its move + And the board should have an X on it + +Scenario: Making Moves + Given I have a started Tic-Tac-Toe game + And it is my turn + And I am playing X + When I enter a position "A1" on the board + And "A1" is not taken + Then the board should have an X on it + And it is now the computer's turn + +Scenario: Making Bad Moves + Given I have a started Tic-Tac-Toe game + And it is my turn + And I am playing X + When I enter a position "A1" on the board + And "A1" is taken + Then computer should ask me for another position "B2" + And it is now the computer's turn + +Scenario: Winning the Game + Given I have a started Tic-Tac-Toe game + And I am playing X + When there are three X's in a row + Then I am declared the winner + And the game ends + +Scenario: Game is a draw + Given I have a started Tic-Tac-Toe game + 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 diff --git a/tic-tac-toe/play_game.rb b/tic-tac-toe/play_game.rb new file mode 100644 index 0000000..3d59473 --- /dev/null +++ b/tic-tac-toe/play_game.rb @@ -0,0 +1,23 @@ +#require './features/step_definitions/tic-tac-toe-steps.rb' +require './tic-tac-toe.rb' + +@game = TicTacToe.new +puts "What is your name?" +@game.player = gets.chomp +puts @game.welcome_player + +until @game.over? + case @game.current_player + when "Computer" + @game.computer_move + when @game.player + @game.indicate_player_turn + @game.player_move + end + puts @game.current_state + @game.determine_winner +end + +puts "You Won!" if @game.player_won? +puts "I Won!" if @game.computer_won? +puts "DRAW!" if @game.draw? diff --git a/tic-tac-toe/tic-tac-toe.rb b/tic-tac-toe/tic-tac-toe.rb new file mode 100644 index 0000000..9bcd26d --- /dev/null +++ b/tic-tac-toe/tic-tac-toe.rb @@ -0,0 +1,139 @@ +class TicTacToe + attr_accessor :player, :welcome_player, :board, :current_player, :computer_symbol, :player_symbol + + def initialize + @board = {a1:nil, a2:nil, a3:nil, b1:nil, b2:nil, b3:nil, c1:nil, c2:nil, c3:nil} + @gamestate = {current_player => :X, :board => @board, :cpu_side => nil} + @winning_lines = [ + [:a1, :a2, :a3], + [:b1, :b2, :b3], + [:c1, :c2, :c3], + [:a1, :b1, :c1], + [:a2, :b2, :c2], + [:a3, :b3, :c3], + [:a1, :b2, :c3], + [:a3, :b2, :c1] + ] + @computer_won, @player_won, @draw = false, false, false + @player = "" + @current_player = nil + @over = false + + end + + def over? + @over + end + + + def detect_win board + result = [false, nil] + @winning_lines.each do |line| + if check_line(line, board, :X) + result = [true, :X] + break + elsif check_line(line, board, :O) + result = [true, :O] + break + end + end + result + end + + def determine_winner + result = detect_win(@board) + if result[0] + winner = result[1] + @over = true + if winner == @computer_symbol + @computer_won = true + elsif winner == @player_symbol + @player_won = true + end + elsif detect_tie + @draw = true + @over = true + else + @over = false + end + end + + def detect_tie + if @board.values.compact.size == 9 + true + else + false + end + end + + def check_line line, board, entry + board[line[0]] == entry and board[line[1]] == entry and board[line[2]] == entry + end + + def welcome_player + if rand(2) == 0 + @current_player = @player + @player_symbol = :X + @computer_symbol = :O + else + @current_player = "Computer" + @player_symbol = :O + @computer_symbol = :X + end + "Welcome " + @player + end + + def computer_won? + @computer_won + end + + def player_won? + @player_won + end + + def draw? + @draw + end + + def computer_move + move = board.keys.sample + if not board[move] + board[move] = @computer_symbol + else + computer_move + end +# corners = [@board[:a1], @board[:a3], @board[:c3], @board[:c1]] +# sides = [@board[:a2], @board[:b1], [@board[:b3], @board[:c2]] +# if @board[:b2] == nil +# @board[:b2] = @computer_symbol +# elsif corners + puts "I will take #{move}." + @current_player = @player + end + + def player_move + move = gets.downcase.chomp.to_sym + if @board.has_key?(move) and @board[move] == nil + @board[move] = @player_symbol + else + puts "Move invalid. Please enter a valid move." + player_move + end + @current_player = "Computer" + end + + def indicate_player_turn + puts "Your turn. Make your move." + end + + def current_state + puts "----------" + puts "| " + @board[:a1].to_s + " | " + @board[:a2].to_s + " | " + @board[:a3].to_s + " |" + puts "----------" + puts "| " + @board[:b1].to_s + " | " + @board[:b2].to_s + " | " + @board[:b3].to_s + " |" + puts "----------" + puts "| " + @board[:c1].to_s + " | " + @board[:c2].to_s + " | " + @board[:c3].to_s + " |" + puts "----------" + end + +end \ No newline at end of file diff --git a/tictactoe b/tictactoe new file mode 160000 index 0000000..43d6d85 --- /dev/null +++ b/tictactoe @@ -0,0 +1 @@ +Subproject commit 43d6d855b7aba545e55d39122177e64c42a02956 diff --git a/week1/exercises/name_printer_spec.rb b/week1/exercises/name_printer_spec.rb new file mode 100644 index 0000000..f0cea23 --- /dev/null +++ b/week1/exercises/name_printer_spec.rb @@ -0,0 +1,15 @@ +describe "NamePrinter Application" do + + context "When Rob is logged in" do + + it "should say Rob" do + + "Rob".should eq "Rob" + + end + + end + + + +end \ No newline at end of file diff --git a/week1/exercises/rspec_spec.rb b/week1/exercises/rspec_spec.rb index 1e0a8ef..e1b1cf9 100644 --- a/week1/exercises/rspec_spec.rb +++ b/week1/exercises/rspec_spec.rb @@ -77,15 +77,20 @@ # Fix the Failing Test # Order of Operations is Please Excuse My Dear Aunt Sally: # Parentheses, Exponents, Multiplication, Division, Addition, Subtraction - (1+2-5*6/2).should eq -13 + (1+1-5*6/2).should eq -13 end it "should count the characters in your name" do - pending + "Rob".should have(3).characters end - it "should check basic math" + it "should check basic math" do + (1+1).should eq 2 + end + - it "should check basic spelling" + it "should check basic spelling" do + "Rob".should include("b") + end end diff --git a/week1/homework/questions.txt b/week1/homework/questions.txt index bd581a6..a46e5c3 100644 --- a/week1/homework/questions.txt +++ b/week1/homework/questions.txt @@ -3,13 +3,23 @@ Chapter 3 Classes, Objects, and Variables p.86-90 Strings (Strings section in Chapter 6 Standard Types) 1. What is an object? +Objects are any pieces of information that can be manipulated in Ruby. 2. What is a variable? +A variable is a reference to an object. If an object change, so does the reference. If there's more than one variable pointing to the object, all variables change when the object changes. 3. What is the difference between an object and a class? +Classes contain both the state of the data and methods that manipulate the data. Objects don't need to contain both, but can do so. Every class is an object, but not every object is a class. 4. What is a String? +Strings are sequences of characters, either printable characters or binary data. -5. What are three messages that I can send to a string object? Hint: think methods +5. What are three messages that I can send to a string object? Hint: think methods? +squeeze, which eliminates long runs of repeated characters (creates new string unless "squeeze!" is used, which modifies it in place) +split, which splits the string on given delimiters (default is a space) and returns a CSV list of the splitted string. +scan, which returns the first part of the string which matches a regular expression 6. What are two ways of defining a String literal? Bonus: What is the difference between the two? +Single and double quotes are the two different ways of defining a string literal. The double quote supports many more escape sequences. + +Other ways include #Q, #q, which are similar to single and double quotes except with coder-chosen delimiting characters, and "here documents," which is weird. \ 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..0ad8fea 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 count the charaters" do + @mystring.length should_not be_nil + 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"))' + @mystring.encoding should eq (Encoding.find("UTF-8"))' end end end diff --git a/week2/exercises/mad_libs.rb b/week2/exercises/mad_libs.rb index 3af5583..b2198e0 100644 --- a/week2/exercises/mad_libs.rb +++ b/week2/exercises/mad_libs.rb @@ -6,5 +6,5 @@ verb_past_tense = gets.chomp puts "What does the #{noun} say?" says = gets.chomp -story = "The #{adjective} #{noun} #{verb_past_tense} past the graveyard and says #{says}" +story = "The #{adjective} #{noun} #{verb_past_tense} past the graveyard and said #{says}" puts story diff --git a/week2/homework/book.rb b/week2/homework/book.rb new file mode 100644 index 0000000..92277bb --- /dev/null +++ b/week2/homework/book.rb @@ -0,0 +1,26 @@ +class Book + attr_accessor :title + attr_reader :page_count + +@@book_count = 0 + + def self.book_count + @@book_count + end + + def initialize title = "Not Set", page_count = 0 + @@book_count += 1 + @title=title + @page_count = page_count + + end + + def test + @test = "hello!" + end + + def out_put_test + puts @test + puts @@book_count + end +end \ No newline at end of file diff --git a/week2/homework/book_spec.rb b/week2/homework/book_spec.rb new file mode 100644 index 0000000..bcfedb0 --- /dev/null +++ b/week2/homework/book_spec.rb @@ -0,0 +1,45 @@ +require './book' + +describe Book do + + context "::book_count" do + it "should increment book counts correctly" do + Book.new + Book.new + Book.new + Book.book_count.should eq 3 + end + end + + + context "::new" do + + it "should set some defaults" do + Book.new.title.should eq "Not Set" + end + + it "should allow us to set the pagecount" do + book = Book.new "Harry Potter", 5 + book.page_count.should eq 5 + end + end + + context "#title" do + + before :each do + @book = Book.new + end + + it "should have a title" do + @book.should respond_to "title" + end + + it "should allow me to set the title" do + @book.title = "Snow Crash" + @book.title.should eq "Snow Crash" + end + + + + end +end \ No newline at end of file diff --git a/week2/homework/calculator.rb b/week2/homework/calculator.rb new file mode 100644 index 0000000..b6e40be --- /dev/null +++ b/week2/homework/calculator.rb @@ -0,0 +1,25 @@ +module Calculator + def sum(list) + s = 0 + list.each {|i| s +=i} + s + end + + def multiply(arg1, arg2=0) + p = 1 + if arg1.is_a?(Array) + arg1.each {|i| p *= i} + p + else + arg1 * arg2 + end + + def pow(arg1, arg2) + p=1 + (arg2).times{p *= arg1} + p + end + + def factorial(arg) + multiply((1..arg).to_a) +end \ No newline at end of file diff --git a/week2/homework/questions.txt b/week2/homework/questions.txt index 939e42d..96c6d62 100644 --- a/week2/homework/questions.txt +++ b/week2/homework/questions.txt @@ -3,11 +3,16 @@ Containers, Blocks, and Iterators Sharing Functionality: Inheritance, Modules, and Mixins 1. What is the difference between a Hash and an Array? +Both use keys to identify data points, but in a hash the keys can be any object while in an array they are always sequential integers. 2. When would you use an Array over a Hash and vice versa? +Arrays are faster for when processing time is at a premium, but they don't offer the flexibility of hashes. If the task can be reasonably done with an array, it will usually be faster, but for more complicated tasks hashes will be necessary. 3. What is a module? Enumerable is a built in Ruby module, what is it? +Modules are groups of methods, classes, and constants. They don't need to be initialized, support mixins, and provide a distinct namespace to prevent name clashes. Enumerable is a module that supports a number of functions related to iterating over elements of a collection. 4. Can you inherit more than one thing in Ruby? How could you get around this problem? +Ruby classes can only inherit from parents, grandparents, and so on, all the way up to BasicObject. Mixins allow Ruby modules to use other modules without regard for parenthood. 5. What is the difference between a Module and a Class? +Classes inherit directly from parents, while modules gain functionality from mixins. \ No newline at end of file diff --git a/week2/homework/simon_says.rb b/week2/homework/simon_says.rb new file mode 100644 index 0000000..c9d6377 --- /dev/null +++ b/week2/homework/simon_says.rb @@ -0,0 +1,24 @@ +module SimonSays + include Enumerable + + def echo(arg) + arg + end + + def shout(arg) + arg.upcase + end + + def repeat(word, repetitions = 2) + ((word + " ")*repetitions).chop + end + + def start_of_word(word, length) + word[0,length] + end + + def first_word(sentence) + a = sentence.split + a[0] + 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..9e5030e --- /dev/null +++ b/week3/homework/calculator.rb @@ -0,0 +1,22 @@ +class Calculator + def sum list + s = 0 + list.each {|i| s +=i} + s + end + + def multiply *input + input.flatten.inject(:*) + end + + def pow arg1, arg2 + p=1 + (arg2).times{p *= arg1} + p + end + + def factorial arg + return 1 if arg==0 + multiply((1..arg).to_a) + end +end \ No newline at end of file diff --git a/week3/homework/calculator_spec.rb b/week3/homework/calculator_spec.rb index 5a418ed..d0c06e3 100644 --- a/week3/homework/calculator_spec.rb +++ b/week3/homework/calculator_spec.rb @@ -27,42 +27,42 @@ # 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 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 + 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 + p = 1 + 32.times{ p *= 2 } + @calculator.pow(2,32).should eq p end # http://en.wikipedia.org/wiki/Factorial describe "#factorial" do it "computes the factorial of 0" do - @calculator.fac(0).should eq 1 + @calculator.fac(0).should eq 1 end it "computes the factorial of 1" do - @calculator.fac(1).should eq 1 + @calculator.fac(1).should eq 1 end it "computes the factorial of 2" do - @calculator.fac(2).should eq 2 + @calculator.fac(2).should eq 2 end it "computes the factorial of 5" do - @calculator.fac(5).should eq 120 + @calculator.fac(5).should eq 120 end it "computes the factorial of 10" do - @calculator.fac(10).should eq 3628800 + @calculator.fac(10).should eq 3628800 end end -end +end \ No newline at end of file diff --git a/week3/homework/questions.txt b/week3/homework/questions.txt index dfb158d..2fe29fa 100644 --- a/week3/homework/questions.txt +++ b/week3/homework/questions.txt @@ -5,11 +5,16 @@ Please Read: - Chapter 22 The Ruby Language: basic types (symbols), variables and constants 1. What is a symbol? +Symbols are constants that don't have to be declared or given value. They are often given as keys for hashes. 2. What is the difference between a symbol and a string? +A string represents the characters it contains and has a number of functions that can be applied to it. If it is used in a variable or constant, it must be declared and saved/assigned. A symbol does not have to be declared or assigned, and can't be searched through or changed like a string. 3. What is a block and how do I call a block? +Blocks are pieces of code meant to be iterated multiple times on another piece of code. To call, you need to give the block arguments and to surround it with {} (usually if single-line) or do/end (usually multi-line). 4. How do I pass a block to a method? What is the method signature? +To pass a block to a method, the method is called with a block and whenever the keyword "yield" occurs, the block will be run. 5. Where would you use regular expressions? +Regular expressions are used to match parts of strings to certain patterns. These patterns can be specific words, symbols, or user-defined types of strings (e.g. searching for something that looks like an email address by looking for text followed by @ followed by text, a ., and a bit more text.) \ No newline at end of file diff --git a/week4/class_materials/monster.rb b/week4/class_materials/monster.rb index 013c3d2..69ead4b 100644 --- a/week4/class_materials/monster.rb +++ b/week4/class_materials/monster.rb @@ -11,4 +11,4 @@ def initialize(noc, legs, name="Monster", vul = [], dangers = []) @dangers = dangers @legs = legs end -end +end \ No newline at end of file diff --git a/week4/class_materials/nano.rb b/week4/class_materials/nano.rb new file mode 100644 index 0000000..220dbd7 --- /dev/null +++ b/week4/class_materials/nano.rb @@ -0,0 +1,76 @@ +stream = "the floor length gown of a forgotten time wouldn't know the first thing that hit it before it lost its way among the roses. no stoppage time for the logging industry, no stoppage time for anyone at all. crying demons don't look to the sky, lost souls stay lost forever unless they are found, they cannot find themselves. turn over every stone until the story is different than how you found it. leave no trace, jump in place. campfire effigy for you and all your kin. require footage, file not found. file in a cabinet in a basement in the long-forgotten alleyway that you probably remember after all. look at me, look at me, don't look at me. cry all night long, let it cry, cry it out. rub some dirt on it. push it down push a pill shove your way through the train wearing a jacket. make it in your sleep. be rude to the interviewer. be above it all. mud + mud won't know who it was what it did. stick your flag in time. make a mark, say hi to mark. creme brule went wrong, kitchen on fire, dancing sims. shoes fit wrong, nobody to hire, look at him. crayola factory burns down, crayola factory melts instead. brown slurry, no fatalities. just dead people. nobody's fate changed, just a change of pace for the fate. under the eaves neighbors gather and talk about it. 'who could have known' 'what can we do' 'where will we go'. small stories in the kitchen. father brother aunt sister's coworker friend cousin enemy frenemy was the last foreman to see the signs before the smoke cleared. a hall of cost. caustic fumes. monoxide. dioxide. not fit to breathe, too heavy, too weighted, + not like a plane in space. + empty air with no air a fighting chance against the sun, radiation on your arm, your leg, robot arm grabs the cargo, brings it to the port. six people at a time, three seats on the escape pod. americans first, no american's died in space yet and by god it will stay that way. + satellite collides with satellite collides with satellite collides with satellite. debris orbits eccentrically. funny debris. wrong in the head. wrong for the globe. debris greets the next flight, hangs a lei around its neck. mahalo. peace generosity velocity. kinetic gratitude. aloha more debris. GPS watches it unfold. map watches unfolding. orbit will decay, delay delay delay. elliptical geostationary. satellite moves on, earth stays in place. celestial breakup. it's just not working out. i've changed. but i love you. i know, i love you too. but your gravitational field was inconsistent with that of a perfect sphere of uniform density. better than the moon. i never loved the moon. + + crybaby cry. worry about the future. think about the job you'll have and you'll hate every day and rapid delay and betray and gray gray gray inlaid wood, desk for dirk. dumb name, dumb baby. dumbbell. dirk in the gym doubts his form doubts filling out forms doubts that his arms will fill out in time for the promotional support furnished by gold's gym: where your muscles go to die and be reborn stronger. phoenix in pink strings. no flames, just pain. feel the burn. reborn dirk, reburn dirk. dirk cries, shits pants. cotton plastic pants. take a nappy. + + cradled grave in a treetop. build a nest, eagles watching. vigilant justice, supreme courtship has sailed, nina the pinta and the sandra day o'connoria. get tested today. get bent today. here lies beavis and butthead; they never ruled. science ruled. bill nye wants a quiet meal alone, never left alone. the brownian motion of black coffee and the green onions in the egg whites. scattered to the plate. shovels entropy into his mouth, dreads having to wake up and fight this feeling, heat will die after the rest of us but we worry more about its death than our own. no parent should have to bury their basic fundamental physical state. family tree is a ray vector. infinitely extends upward, finitely extends downward. my great grandfather was a chemist. my great x 10^39 grandfather was a mote of hydrogen created in the second femtosecond of existence. second second, second measurement, different result. second result. first result negative, second positive. opposites attract, results marry. proton and electron in protracted divorce, ionic bond, jealous lover flourine. the man who shot liberty valence electron. high momentum, no mass. infinity times zero is two. light speed nothingness on the skin makes DNA go crazy mixup, cells filled with DAN. spread and multiply. be fruitful and metastasize. go forth, crabby cells. wrong month for cancer; you have prostate aries. i'm sorry, doctor? so am i. + + create a job. make work happen. break the window, pay the breaker, pay the fixer. job creation in seven days. on the first day he created baristas. on the second day he created the beasts and the customers. on the third and fourth days he made bail. bail out the economy, a sinking ship. rest on the bottom, improvised coral reef. economic growth, biodiversify your portfolio. invest in future generations of colorful camouflage. attention grabbing invisibility. the orange and white striped hand of adam smith. john maynard florida keynes argues for government spending. for every dollar spent on public works, 1.7 fish are created. make enough fish for a job. teach at a school. fish don't learn. fish don't plan for the future. water gets warmer, fish get oranger. drought conditions on the reef. keep a bucket of water or sand nearby. + + day 2 + rest for the wicked witch. melt with water send a new signal to the monkeys--new marching orders; new flying orders. create something the monkeys won't believe. oz for an ape, emerald city emerald canopy. gibbous gibbon moon. react with appropriate courage brains and homeliness. dorothy reminds toto that home was a shithole and nobody wanted to go there in the first place. get out of there. natural disaster naturally rebuilds home; one in a million chance. entropy in reverse. the only measure of which way time goes. entropy knows. one in a trillion chance. one in a million in a billion. house lands on witch, precision guided house. weaponized tornado. + + climb mount everest. the most ever. bring air bring supplies bring a bunch of men to carry them bring 50,000 dollars bring a camera. go into the death zone. walk by frozen corpses. say hello. how do you do. i am a mountain climber. oh, i see. how do you like being a frozen corpse. you were a mountain climber too? what a small world. small world. live on the crust. edge of the pie. pie are squared. pie are circular. pie are sphered. send a signal. pie is known. pie is rational. pie reminds us that it was always there but we just didn't understand it. e is lonely and abstract. e to the x is e to the x is e to the x is e to the x. unexciting infinite irrational constant. boring complexity. plain ol' unplumbed depths. + + bathysphere to the deep. ocean trench, mariana. woman trench. mariana's trench. high pressure situation. cold water deep below, fish make their own light. who makes light for wildebeest? humboldt squid make red and white patterns. dazzle your prey, dress to kill. humble humboldt. + +halftime in america. eat orange slices, america. analyze mistakes, revise the game plan. commentators shout. is prez a good qb. would vp be better. clipboard president. call plays, let them know their loved ones died for their country. make greedy choices. go for it on fourth and two. reverse the play, now it's twooth and four. fight tooth and nail. criticize the OC. criticize someone who's in control. criticize the angle of attack. take a differnt angle, different stance. three point stance, three point plan. crush the competition. compete with your crush. romance your rival. react with approval. + +accessible art, handicapped paintings. ramp to sculpture. exit to the left. pick up art and throw it across the room. injure the walls. react with grace under fire. fire to the gallery. fire the peanut gallery, they're making too much noise. golf clap a team player. at the stadium shout out your lungs. the sound bounces side to side up and down absorbed by the 70,000 absorbed by the benches and bleachers, whatever isn't reflected must be absorbed. blue wavelengths of sound reflect. red and green absorbed. the scoreboard is blue. the operator is blue. no more hand-operation. automatic scoreboard eliminates jobs for hardworking pastimes. pass the time with baseball, don't react with fear or disappointment. watch the pitcher pitch. pour a pitcher. pitcher broke the mold, can't be poured anymore. pitcher hardens over time, ligaments brittle. bone spurs in elbow. torn labrum, thomas james surgery. thomas james the fourth shoulder he's torn. no backup elbow, he does it all himself. no relief human. go six innings, don't give up runs. quality start to a human life. let the bullpen take it from here. young men handles the 7th and 8th. lets in a run, crowd boos. tie ballgame. no chance for a W now. starter sighs. better luck next life. good ERA. 9th inning closer. closer than ever. 9th inning arrives. closer pitches. closer to zone, no walks. batters reach base only on own merits. starter watches. life, game almost over. praying for a miracle. miracle comes; tie game. crowd boos; poor starter. no W at all. bottom 9th. no time to waste. all the pastime in the world. starter tense. present tense. starter presently tense second batter makes double. first batter is out, out of game, out of ballpark. hit the showers. at home. hit anything you want, just don't do it here. you don't have to destroy home, but you can't damage here. third batter watches strike one strike two ball one ball two ball three foul one foul two foul foul foul foul odor in the locker room reminds him of middle school gym, same stench same feel same shouting. foul again. never smells good. strike zone, swing. hit the correct thing in the correct place. damage a baseball. punish it at relative velocity of 200+ mph. ball to center left. north north west. center by center left. right fielder flees shadow of flying thing. death to flying things. trips, falls, flies harmlessly by. speed wasn't enough, stadium wasn't enough. blame the stadium, not the fielder. don't hate the outcome, hate the team. pitcher gets a W but now it's over. no extra innings. starter goes to locker room. it stinks. + + " + +story = "One figure spotted another crossing the bridge. The latter swiveled head in every direction, searching for anyone paying attention. The former was comfortable in the knowledge that no attention was being paid to it. The latter figure finally spots the former. The latter looked exactly where it was told to look, and after a moment finally spotted the former. Latter started to call out, stopped herself, started to wave, fought the impulse, has a dozen more half-formed movements propagated through her brain and body. If anyone had been watching, they would have been paying attention now. After thirty more of the most chalant steps ever attempted by humanity, she reached the figure. She tried to make out the dim figure in the alcove. It was only six feet in front of her, but the moon was facing the wrong direction. Former stared back at her. They shared an expectant moment. Latter realized. She looked to the night sky, trying to remember. + 'Crap.' said Latter. + 'Okay.' said the alcove. + 'No, I mean I don't--' + 'Okay.' There was a rustle and a muffled clink in the dark, as though the alcove was pulling something metal out of a pocket. + 'No, but--what if I'm a spy?' + There was a small pause that could indicate either mild amusement or intense loathing. + 'Are you a spy?' + 'No!' + 'Okay.' + 'What if I was?' + 'Then you wouldn't walk like that.' + 'What if I was a clever spy?' + 'Then you wouldn't forget the password after being told three times.' + 'The meetings are supposed to be anonymous!' + 'Then walk anonymously.' + Latter ran out of words. There was another pause as the alcove waited to see if anything else was forthcoming, then she began to reach for her pocket again. + 'Drainage Basin!' + There was another pause from the alcove. The password hung between buildings like a clothesline. + Bright orange light flared for a moment and briefly illuminated both figures. + The figure in the alcove wouldn't strike you as the kind of figure to be standing in a dark alcove late at night, waiting for someone to say 'drainage basin!' at her. She would strike you much more as the kind of figure to partner in a a small business selling fancy useless things to fancy useless people, in whose advertising the term 'artisinal' would figure heavily. + Former wouldn't strike you. She had a chubby, guileless face that you would naturally trusted not to hurt you, at least not intentionally. + The match was extinguished and the alcove was now a moving orange dot and the smell of smoke. Former waited, but there was no movement from the alcove other than the dot. + 'Well?' + The dot was silent. When it finally spoke, the dot had a much softer voice. + 'Look, honey--' + The dot searched for the right words. + 'I think you might be in a little over your head.' + 'I can do it! They said I could do it! Don't you trust them?' + 'Trust who?' + 'The people at the mee--' + 'No. Not the people at the meeting. Because the meeting didn't take place, remember? Just like this conversation? And the transportation of the object in my pocket? + 'Oh.' + 'I think it would be best for everyone if you just went for a late night stroll for no particular reason and then returned home, with nothing in your pockets and no delivery to make. The next time you're at a place where certain people certainly are not, they can completely fail to ask you to complete a task to which you are better suited. + 'Oh.' + 'Alright?' + 'Yeah. Okay.' + The dot fell to the ground and disappeared. The alcove spoke, much more harshly. + 'Scram.' + Former slowly turned away and back to the main road. Keeping her head and feet down, she walked with such quiet, inward-facing disappointment that when the alcove looked at her again, it barely recognized her. + + day 2 + There was a bridge. Primarily constructed from basalt quarried 15 kilometers to this location, cut by masons and stuck together with high quality mortar. A city contract, with all its problems and rewards. Went to the lowest bidder, of course, but a decent quality build nonetheless. The bridge can withstand its own weight, of course, and then another three quarters of that on top of it. Not the best ratio for a bridge, but decent enough for the traffic that would be going on it. A this moment, several things were affecting the bridge. For one, the temperature was ten degrees centigrade, which caused some mild contraction. Basalt + + " + #"bridget" +a= stream.split.length +b =story.split.length +puts a +puts b +puts a+b \ No newline at end of file diff --git a/week4/exercises/worker.rb b/week4/exercises/worker.rb new file mode 100644 index 0000000..195a4c6 --- /dev/null +++ b/week4/exercises/worker.rb @@ -0,0 +1,8 @@ +class Worker + def self.work(rep=1) +# res = 0 +# rep.times {res = yield } +# res + rep.times.inject(nil){yield} + end +end \ No newline at end of file diff --git a/week4/exercises/worker_spec.rb b/week4/exercises/worker_spec.rb index dfc6f02..794a4a5 100644 --- a/week4/exercises/worker_spec.rb +++ b/week4/exercises/worker_spec.rb @@ -1,4 +1,4 @@ -require "#{File.dirname(__FILE__)}/worker" +require "#{File.dirname(__FILE__)}/worker.rb" describe Worker do diff --git a/week4/homework/questions.txt b/week4/homework/questions.txt index bc1ab7c..6991cb3 100644 --- a/week4/homework/questions.txt +++ b/week4/homework/questions.txt @@ -3,7 +3,18 @@ Chapter 10 Basic Input and Output The Rake Gem: http://rake.rubyforge.org/ 1. How does Ruby read files? +Ruby reads files by opening them and iterating through by line or by byte. + 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 defines IO streams representing directories in the file system. They allow the user to find and list directories and their contents. + 4. What is an IO object? +IO objects are channels between Ruby and other programs or resources--a single object can carry information both ways. + 5. What is rake and what is it used for? What is a rake task? +Rake is a way to automate common tasks, especially tasks that might have to be done in a certain order, for instance in the creation of a rails server. A rake task can be something like creating a new database and then populating it with dummy data so that a Ruby program can be tested on it. \ No newline at end of file diff --git a/week5/class_materials/Rakefile.rb b/week5/class_materials/Rakefile.rb new file mode 100644 index 0000000..5206753 --- /dev/null +++ b/week5/class_materials/Rakefile.rb @@ -0,0 +1,10 @@ +task :default => [:hello_world] + +desc "This outputs hello world!" +task :hello_world do + puts test +end + +def test + "tequila" +end diff --git a/week5/exercises/Rakefile.rb b/week5/exercises/Rakefile.rb new file mode 100644 index 0000000..7ec7257 --- /dev/null +++ b/week5/exercises/Rakefile.rb @@ -0,0 +1,24 @@ +#reads all the lines and outputs them +task :default => [:names, :make_directory, :indiv_directory] + +desc "reads all the lines in the file and outputs them" +task :names do + File.open("names") do |file| + file.each_line {|line| puts line} + end +end + + +#creates a 'class' directory +desc "make a 'class' directory" +task :make_directory do + Dir.mkdir("class") unless Dir.exists? 'class' +end + +#dependent on class directory task, makes directory in class directory for each name +desc "make individual directories for each student" +task :indiv_directory do + a = [] + Dir.chdir("class") + a.each {|n| Dir.mkdir(n)} +end diff --git a/week7/homework/play_game.rb b/week7/homework/play_game.rb index 0535830..7b99f10 100644 --- a/week7/homework/play_game.rb +++ b/week7/homework/play_game.rb @@ -10,7 +10,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/week9/class_materials/exception.rb b/week9/class_materials/exception.rb new file mode 100644 index 0000000..342acbe --- /dev/null +++ b/week9/class_materials/exception.rb @@ -0,0 +1,24 @@ +class RobError < Exception + def message + "SOMETHING FUK DUP" + end +end + +begin + raise "YIPES" + File.open('hello.txt') +rescue => e + puts "Something went wrong." +rescue Errno::ENOENT => e + puts "Well shoot. Doesn't look like that's a file." +ensure + puts "We're done here." +end +catch :yipes do + i = 0 + sleep(2) + while i<10 + throw :yipes if i == 5 + puts i+=1 + end +end \ No newline at end of file