Skip to content

Instantly share code, notes, and snippets.

@eddroid
Last active October 7, 2015 21:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save eddroid/cfdda1415eebef488f64 to your computer and use it in GitHub Desktop.
Save eddroid/cfdda1415eebef488f64 to your computer and use it in GitHub Desktop.
Cohort 7
require 'rspec/autorun'
# A Set is an Array that is automatically de-duplicated (uniq'd)
require 'set'
####
## Coordinate
##
## an x,y coordinate pair
####
class Coordinate
attr_accessor :x, :y
def initialize(x, y)
@x = x
@y = y
end
# The neighbording coordinate pairs in 2-d space.
def neighbors
x_options = [x-1, x, x+1]
y_options = [y-1, y, y+1]
all_coords = Set.new(x_options.product(y_options))
all_coords.delete([x,y])
end
end
####
## Coordinate Test
####
describe Coordinate do
# random (x,y) coordinate
let(:x){rand(100_000)}
let(:y){rand(100_000)}
subject { described_class.new x, y }
it 'has coordinates' do
expect(subject.x).to eq x
expect(subject.y).to eq y
end
it "correctly calculates a set of neighbor coordinates" do
# northwest, north, northeast
# west, (x,y), east
# southwest, south, southeast
expected_neighbors = Set.new([
[x-1, y-1], [x-1, y], [x-1, y+1],
[x, y-1], [x, y+1],
[x+1, y-1], [x+1, y], [x+1, y+1]
])
expect(subject.neighbors).to eq expected_neighbors
end
end
####
## Cell
##
## A coordinate & a state (:alive, :dead)
####
class Cell
attr_accessor :state, :coordinate
def initialize(coordinate, state)
@coordinate = coordinate
@state = state
end
# Given a number of living neighbors, return the new state
# :alive or :dead
def survives(num_neighbors)
if @state == :alive
next_state_when_alive(num_neighbors)
else
next_state_when_dead(num_neighbors)
end
end
# Create a new cell corresponding to the next state
def next(num_neighbors)
next_state = survives(num_neighbors)
self.class.new(@coordinate, next_state)
end
def alive?
state == :alive
end
def next_state_when_alive(num_neighbors)
[2, 3].include?(num_neighbors) ? :alive : :dead
end
def next_state_when_dead(neighbors)
neighbors == 3 ? :alive : :dead
end
end
####
## Cell test
####
describe Cell do
let(:coordinate) { Coordinate.new 0, 0 }
subject { described_class.new coordinate, :alive }
it 'has a coordinate' do
expect(subject.coordinate).to eq coordinate
end
describe 'when alive' do
[0, 1, 4, 5, 6, 7, 8].each do |live_neighbors|
it "dies with #{live_neighbors} neighbors" do
expect(subject.next(live_neighbors)).to_not be_alive
end
end
[2, 3].each do |live_neighbors|
it 'remains alive with #{live_neighbors} live neighbors' do
expect(subject.next(live_neighbors)).to be_alive
end
end
end
describe 'when dead' do
subject { described_class.new coordinate, :dead }
[0, 1, 2, 4, 5, 6, 7, 8].each do |live_neighbors|
it "remains dead with #{live_neighbors} neighbors" do
expect(subject.next(live_neighbors)).to_not be_alive
end
end
it 'lives with 3 live neighbors' do
expect(subject.next(3)).to be_alive
end
end
end
####
## Board
####
class Board
attr_accessor :live_cells
def initialize(live_cells)
@live_cells = Set.new(live_cells)
end
# alternative intializer
def self.new_board_from_coordinate_list(coords)
live_cells = coords.map do |xy|
coord = Coordinate.new(*xy) # same as x, y
Cell.new(coord, :alive)
end
new(live_cells)
end
# next board
# wrong, but works for now
def next
self
end
# All the live cells and all their neighbors
#
# For efficiency when calculating the next board,
# these are the only cells we need to look at.
def under_consideration
@live_cells.reduce(Set.new) do |cells_to_consider, live_cell|
cells_to_consider.union(live_cell.coordinate.neighbors)
end
end
end
####
## Board test
####
describe Board do
# -
let(:blank_board) do
described_class.new_board_from_coordinate_list([])
end
# -----
# -***-
# -----
let(:blinker_board) do
described_class.new_board_from_coordinate_list([
[-1, 0], [0,0], [1,0]
])
end
# ---
# -*-
# -*-
# -*-
# ---
let(:blonker_board) do
described_class.new_board_from_coordinate_list([
[0, -1], [0,0], [0,1]
])
end
describe 'square board' do
# ----
# -**-
# -**-
# ----
#
# The next board should look like this one.
let(:square_board) do
described_class.new_board_from_coordinate_list([
[0,0], [1,0],
[0,1], [1,1]
])
end
it 'has a set of live cells' do
expect(square_board.live_cells).to be_a Set
expect(square_board.live_cells.length).to eq 4
square_board.live_cells.each do |cell|
expect(cell).to be_a Cell
end
end
it 'has a set of cells under consideration' do
expect(square_board.under_consideration.length).to eq 16
end
it 'iterates to another square board' do
expect(square_board.next).to eq square_board
end
end
it 'has a set of cells under consideration' do
# no cells at all
expect(blank_board.under_consideration.length).to eq 0
# 3 cells + 12 neighbors
expect(blinker_board.under_consideration.length).to eq 15
expect(blinker_board.under_consideration.length).to eq 15
end
it 'iterates a blank board correctly' do
expect(blank_board.next).to eq blank_board
end
it 'iterates a blinker board correctly' do
# expect(blinker_board.next).to eq blonker_board
# expect(blonker_board.next).to eq blinker_board
end
end
require 'httparty'
class Siskel
attr_reader :title, :rating, :year, :plot
def initialize(title, opts = {})
year = opts[:year]
plot_type = opts[:plot]
movie = HTTParty.get(
"http://www.omdbapi.com/?t=#{title}&y=#{year}&plot=#{plot_type}&tomatoes=true").parsed_response
@tomato_meter = movie["tomatoMeter"].to_f
#{"Title"=>"The Hangover", "Year"=>"2009", "Rated"=>"R", "Released"=>"05 Jun 2009", "Runtime"=>"100 min", "Genre"=>"Comedy", "Director"=>"Todd Phillips", "Writer"=>"Jon Lucas, Scott Moore", "Actors"=>"Bradley Cooper, Ed Helms, Zach Galifianakis, Justin Bartha", "Plot"=>"Three buddies wake up from a bachelor party in Las Vegas, with no memory of the previous night and the bachelor missing. They make their way around the city in order to find their friend before his wedding.", "Language"=>"English", "Country"=>"USA, Germany", "Awards"=>"Won 1 Golden Globe. Another 10 wins & 25 nominations.", "Poster"=>"http://ia.media-imdb.com/images/M/MV5BMTU1MDA1MTYwMF5BMl5BanBnXkFtZTcwMDcxMzA1Mg@@._V1_SX300.jpg", "Metascore"=>"73", "imdbRating"=>"7.8", "imdbVotes"=>"541,254", "imdbID"=>"tt1119646", "Type"=>"movie", "Response"=>"True"}
@rating = movie["Rated"]
@year = movie["Year"]
@plot = movie["Plot"]
# {"Response"=>"False", "Error"=>"Movie not found!"}
@title = movie['Title'] || movie['Error']
#{"Title"=>"Daredevil", "Year"=>"2003", "Rated"=>"PG-13", "Released"=>"14 Feb 2003", "Runtime"=>"103 min", "Genre"=>"Action, Crime, Fantasy", "Director"=>"Mark Steven Johnson", "Writer"=>"Mark Steven Johnson (screenplay)", "Actors"=>"Ben Affleck, Jennifer Garner, Colin Farrell, Michael Clarke Duncan", "Plot"=>"A man blinded by toxic waste which also enhanced his remaining senses fights crime as an acrobatic martial arts superhero.", "Language"=>"English, Greek, Italian", "Country"=>"USA", "Awards"=>"4 wins & 16 nominations.", "Poster"=>"http://ia.media-imdb.com/images/M/MV5BMzU3MDUxNjYwNl5BMl5BanBnXkFtZTYwNzQ3Nzc2._V1_SX300.jpg", "Metascore"=>"42", "imdbRating"=>"5.3", "imdbVotes"=>"163,824", "imdbID"=>"tt0287978", "Type"=>"movie", "tomatoMeter"=>"44", "tomatoImage"=>"rotten", "tomatoRating"=>"5.2", "tomatoReviews"=>"221", "tomatoFresh"=>"98", "tomatoRotten"=>"123", "tomatoConsensus"=>"While Ben Affleck fits the role and the story is sporadically interesting, Daredevil is ultimately a dull, brooding origin story that fails to bring anything new to the genre.", "tomatoUserMeter"=>"35", "tomatoUserRating"=>"2.8", "tomatoUserReviews"=>"467245", "DVD"=>"29 Jul 2003", "BoxOffice"=>"$102.5M", "Production"=>"20th Century Fox", "Website"=>"http://www.daredevilmovie.com", "Response"=>"True"}
#{"Title"=>"The Fifth Element", "Year"=>"1997", "Rated"=>"PG-13", "Released"=>"09 May 1997", "Runtime"=>"126 min", "Genre"=>"Action, Adventure, Romance", "Director"=>"Luc Besson", "Writer"=>"Luc Besson (story), Luc Besson (screenplay), Robert Mark Kamen (screenplay)", "Actors"=>"Bruce Willis, Gary Oldman, Ian Holm, Milla Jovovich", "Plot"=>"In the colorful future, a cab driver unwittingly becomes the central figure in the search for a legendary cosmic weapon to keep Evil and Mr Zorg at bay.", "Language"=>"English, Swedish, German", "Country"=>"France", "Awards"=>"Nominated for 1 Oscar. Another 9 wins & 32 nominations.", "Poster"=>"http://ia.media-imdb.com/images/M/MV5BMTkzOTkwNTI4N15BMl5BanBnXkFtZTYwMDIzNzI5._V1_SX300.jpg", "Metascore"=>"52", "imdbRating"=>"7.6", "imdbVotes"=>"314,964", "imdbID"=>"tt0119116", "Type"=>"movie", "tomatoMeter"=>"71", "tomatoImage"=>"fresh", "tomatoRating"=>"6.3", "tomatoReviews"=>"58", "tomatoFresh"=>"41", "tomatoRotten"=>"17", "tomatoConsensus"=>"Visually inventive and gleefully over the top, Luc Besson's The Fifth Element is a fantastic piece of pop sci-fi that never takes itself too seriously.", "tomatoUserMeter"=>"87", "tomatoUserRating"=>"3.7", "tomatoUserReviews"=>"584929", "DVD"=>"09 Dec 1997", "BoxOffice"=>"N/A", "Production"=>"Sony Pictures Home Entertainment", "Website"=>"N/A", "Response"=>"True"}
end
def consensus
if @tomato_meter >= 0 and @tomato_meter <= 50
"Thumbs Down"
else
"Thumbs Up"
end
end
end
class Voter
attr_reader :name
attr_reader :politics
def initialize(name, politics)
@name = name
@politics = politics
end
end
require './voter.rb'
class World
attr_accessor :voters
def initialize
@voters = []
end
def main_menu
puts "What would you like to do?
(C)reate, (L)ist, (U)pdate, or (V)ote"
option = "C" #gets.chomp.upcase
case option
when "C"
create_menu
when "L"
when "U"
when "V"
else
end
end
def create_menu
puts "What would you like to create?
(P)olitician or (V)oter"
create_option = "V" #gets.chomp.upcase
case create_option
when "V"
create_voter_menu
when "P"
else
end
end
def create_voter_menu
puts "Name?"
name = "Ed" #gets.chomp
puts "Politics?
(L)iberal, (C)onservative, (T)ea Party, (S)ocialist, or (N)eutral"
politics = "L" #gets.chomp.upcase
@voters << Voter.new(name, politics)
#main_menu
end
def find_voter(name)
@voters.select do |voter|
voter.name == name
end.first
end
end
def test
voters = [Voter.new("Ed", "Liberal"),
Voter.new("Juha", "Tea Party"),
Voter.new("Jo", "Socialist")]
# p voter.name, voter.politics
# voters = world.voters
# voter = voters.first
# p voter.name, voter.politics
world = World.new
# world.main_menu
world.voters = voters
p world.voters
voter = world.find_voter("Ed")
p voter, voter.class
#world.update_voter(voter)
end
test
# # output the Ruby version
# puts "This is the Ruby version (puts)"
# puts RUBY_VERSION
# puts "This is the Ruby version (p)"
# p RUBY_VERSION # p is for developers
# [1,2,3]
# # This is
# # a multiline
# # comment.
# 1.+()
# puts <<END
# You can put a large string in here.
# It can contain "quotes" and 'quotes'
# You can even use newlines (\n) or just his enter.
# You will still need to escape the backslash (\\).
# You can have leading whitespace.
# And everything will b included up to the END below this line.
# END
# bill = 40
# tip_percent = 0.20
# num_people = 3
# tip = bill * tip_percent
# total = bill + tip
# my_share = total / num_people
# puts "My share of a ${bill} bill with a #{tip_percent}% tip: $" + my_share.to_s
# puts "My share of a $40 bill with a 20% tip: $#{my_share}"
# puts "The value of 1 + 1 #\{ is #{1+1}"
# puts '#{'
# arr = [1,2,3]
# p arr.delete(3)
# p arr
# str = "ACME Company"
# p str.downcase!
# p str
# n = 1
# # n.next!
# n = n.next
# p n
# n = 4
# n = n / 2
# p n
# n = 1
# n += 1 # n = n + 1
# puts n
# n -= 1 # n = n - 1
# puts n
# n *= 2
# puts n
# n /= 2
# puts n
# n++ doesn't work in Ruby
# p 1 + 1
# p "1" + "1"
# p [1,2] + [3,4]
# arr = [1,2,3]
# arr += [4,5,6]
# p arr
# value = nil
# value ||= 1 # default value to 1
# p value
# unknown_value = unknown_value || 2
# # unknown_value ||= 2 # unknown_value = unknown_value || 2
# p unknown_value
# unknown_number = unknown_number + 1
# p unknown_number
# value = false
# value ||= true # default value to true
# p value
# CONST = 1
# CONST = 2
# puts "Hello world"
# p CONST
# p RUBY_VERSION
# # RUBY_VERSION = "1.2.3"
# puts "THe new Ruby version #{RUBY_VERSION}"
# p Math::PI, Math::E
# PI = 3.14
# p Math::PI, Math::E
# dead_people = ["Ethel", "Mortimer", "Buford"]
# alive_people = ["Kelly", "Joe", "Megan"]
# sick_people = alive_people.slice(0, 2)
# name = "Mortimer"
# if dead_people.include? name
# puts "Don't send questionnaire to #{name}"
# elsif sick_people.include? name
# puts "Send a questionnaire to #{name} later."
# else
# puts "Send questionnaire to #{name}"
# end
# unless dead_people.include? name
# puts "Send it"
# # elsif sick_people.include? name
# # puts "Later"
# else
# puts "Don't send"
# end
# if false
# puts "Hello"
# puts "Hello"
# puts "Hello"
# puts "Hello"
# puts "Hello"
# else
# puts "asdf"
# if true
# puts "true"
# else
# puts "false"
# end
# end
# initialize cats
# cats = []
# number_of_cats = 100
# n = 1
# while (n <= number_of_cats)
# # true means "hat on", false means "hat off"
# cats << true
# n = n.next
# end
# p cats, cats.length
# # 1st pass
# cats1 = []
# n = 1
# while (n <= number_of_cats)
# cats1 << !cats[n-1]
# n = n.next
# end
# p cats1, cats1.length
# # 2nd pass
# cats2 = []
# n = 1
# while (n <= number_of_cats)
# if (n % 2).zero?
# cats2 << !cats1[n-1]
# else
# cats2 << cats1[n-1]
# end
# n = n.next
# end
# p cats2, cats2.size
# # 3rd pass
# cats3 = []
# n = 1
# while (n <= number_of_cats)
# if (n % 3).zero?
# cats3 << !cats2[n-1]
# else
# cats3 << cats2[n-1]
# end
# n = n.next
# end
# p cats3, cats3.size
# The pattern
#
# cats_next = []
# n = 1
# while (n <= number_of_cats)
# if (n % |-> hole in the pattern <-|).zero?
# cats_next << !cats_prev[n-1]
# else
# cats_next << cats_prev[n-1]
# end
# n = n.next
# end
# p cats_next, cats_next.size
####
## Methods
####
# def add_two(number)
# #number = ****
# ###
# number + 2
# ##
# # delete number
# end
# puts add_two(1)
# def add_two(number)
# if number.respond_to? :+
# ## too many people are invited to this party
# # array
# if number.respond_to? :push
# number.push 2
# else
# number + 2
# end
# end
# end
# def test
# puts add_two(1) == 3
# puts add_two(1.0) == 3.0
# puts add_two(9999999999999999999) == (9999999999999999999 + 2)
# puts add_two(nil).nil?
# puts add_two({}).nil?
# p add_two([])
# puts add_two(false)
# puts add_two("")
# end
# test
# def one
# if false
# 0
# end
# end
# p one
# def find_ten
# i = 0
# loop do
# if i == 10
# # stop looping
# # return i
# break
# end
# i += 1
# end
# i
# end
# p find_ten
# def say_hello(name)
# puts "Hello #{name}"
# end
# # say_hello
# say_hello_method = method(:say_hello)
# p say_hello_method.class
# 5.times say_hello_method
# # 5.times say_hello
# 5.times &say_hello_method
# 5.times do
# puts "hello"
# end
# 5.times { |n| puts "Hello #{n*10}" }
# p 5.times.methods.size, [].methods.size
# p 5.times.to_a, [0,1,2,3,4]
# p (0..4).to_a
# p (0...4).to_a
# p (1..100).to_a
# p ("a".."z").to_a
# p (:a..:z).to_a
# [false,"",[],4,{}].each do |item|
# p item
# end
# (10..15).each { |number| p number }
# (1..5).each do |num|
# if num.even?
# puts "Even"
# else
# puts "Odd"
# end
# end
# for num in (1..5)
# p num
# end
# (1..5).each { |num|
# puts num
# }
# command line similar to pipes (|)
# output = (1..5).map do |num|
# num.even? ? "Even" : "Odd"
# end
# puts output
# output = (1..5).map { |num|
# num.even? ? "Even" : "Odd"
# }.map { |even_or_odd|
# even_or_odd.upcase
# }
# p output
# output = (1..5).reject { |num|
# num.even?
# }
# p output
# puts [1,5,3].any? { |n| n.even? }
# puts [2,2,2].all? { |n| n.even? }
# puts [1,1,1].one? { |n| n.even? }
# puts [1,1,2].none? { |n| n.even? }
# def a_method(arg)
# puts arg
# yield
# end
# a_method('stuff') do
# puts "inside block"
# end
# def puts_block
# if block_given?
# puts yield
# else
# puts "No block given"
# end
# end
# puts_block
# puts_block { 'hello' }
# def puts_hello_wyncode
# puts yield(nil, 'Ed')
# end
# puts_hello_wyncode do |speaker, name|
# p name
# "#{speaker}: Hello #{name}"
# end
# def with_lines
# puts "*"*50
# yield
# puts "*"*50
# end
# def say_something(statement)
# with_lines {
# puts statement
# }
# end
# with_lines {
# puts "Multiple lines"
# puts "Of text"
# a = 1 + 1
# puts a
# puts "#{a}"
# puts "GO in here"
# }
# # puts "*"*50
# # puts "Hello World!"
# # puts "*"*50
# say_something("Hello world!")
# # puts "*"*50
# # puts "Welcome to my game!"
# # puts "*"*50
# say_something("welcome to my game!")
def add_two(number = 0, *rest)
if rest.size > 0
puts "Seriously? #{rest}"
end
number + 2
end
# p add_two
# p add_two(1, 2)
# p add_two(1, 2, 3, 4, 5, 6)
# puts "asdf", "asdf", "asdf"
# def add_two(n = 0, opts = {})
# ##
# default_opts = {strings_are_ok: true }
# opts = default_opts.merge(opts)
# ##
# p opts
# if opts[:strings_are_ok]
# # code for handling strings
# elsif opts[:arrays_are_ok]
# # code for array
# else
# n + 1
# end
# end
# def test
# # puts add_two("1", {strings_are_ok: true, nils_are_ok: true})
# # puts add_two("1", {strings_are_ok: true, nils_are_ok: true})
# # puts add_two("1", strings_are_ok: true, nils_are_ok: true, a: "b", c: "d", asdf: "asdf")
# # puts add_two(1, strings_are_ok: false)
# end
# test
# a = 2
# a ||= 1 # a = a || 1
# p a
####
## Classes
####
# class Table
# attr_accessor(:num_legs)
# def initialize(num_legs)
# @tabletop = []
# @num_legs = num_legs
# end
# def put_on(something)
# @tabletop << something
# end
# def look_at
# @tabletop
# end
# # attr_reader :num_legs
# # def num_legs
# # @num_legs
# # end
# # attr_writer :num_legs
# # def num_legs=(new_num_legs)
# # @num_legs = new_num_legs
# # end
# def self.has_legs?
# true
# end
# end
# free methods
# # p Table.class, Table.methods, Table.hash, Table.to_s, Table.nil?
# wooden_table = Table.new(3)
# free methods
# # p wooden_table.class, wooden_table.methods, wooden_table.hash, wooden_table.to_s, wooden_table.nil?
# add new behavior - instance methods
# wooden_table.put_on("something")
# p wooden_table.look_at
# wooden_table.put_on(1)
# p wooden_table.look_at
# # add new attributes
# # puts wooden_table.num_legs
# # wooden_table.num_legs = 4 # same as "wooden_table.num_legs=(4)"
# # puts wooden_table.num_legs
# # class behaviors
# # p Table.has_legs?
# # "blessed" globals
# # $: = 'hello.rb'
# # superclass (parent class)
# class Vehicle
# attr_accessor :engine, :tires
# end
# # subclass1
# class Car < Vehicle
# end
# # subclass 2
# class Motorcycle < Vehicle
# end
# # free methods
# # p Car.class, Car.methods
# # fiat = Car.new
# # free methods
# # p fiat.class, fiat.methods
# # cars have engines (via vehicle)
# # p fiat.engine
# # motorcycles also have engines (via vehicle)
# # ducati = Motorcycle.new
# # p ducati.engine
# # methods are looked up via the ancestor chain
# # p Car.ancestors
# # p Motorcycle.ancestors
# # superclass == first ancestor
# # p Car.superclass, Motorcycle.superclass
# module Talkative
# def speak(statement)
# puts statement
# end
# end
# # require './talkative.rb'
# class Kitt < Car
# include Talkative
# def initialize
# @engine = "supercharged hemi hydro blah blah blah"
# end
# # def speak(statement)
# # puts statement
# # end
# def describe_engine
# puts "My engine is #{@engine}"
# end
# end
# # kitt = Kitt.new
# # p kitt.engine, kitt.tires
# # kitt.speak("hello")
# # kitt.describe_engine
# p Kitt.ancestors, Kitt.superclass
# def call_method1
# method1
# end
# def method1
# puts "I'm method1"
# end
# call_method1
# Table = Class.new("Table")
# class Table
# @@next_table_id = 1
# attr_reader :serial_num
# def self.next_table_id
# @@next_table_id
# end
# def self.set_next_id(number)
# @@next_table_id = number
# end
# def initialize
# @serial_num = @@next_table_id
# @@next_table_id = @@next_table_id.next
# end
# def preview_next_id
# @@next_table_id
# end
# def set_next_id(message)
# @@next_table_id = message
# end
# end
# # p Table.next_table_id
# # Table.set_next_id 5
# # p Table.next_table_id
# ikea_table = Table.new
# # p ikea_table.next_table_id
# # # p ikea_table.serial_num
# macys_table = Table. new
# # p macys_table.serial_num
# # macys_table.next_table_id
# p ikea_table.preview_next_id
# p macys_table.preview_next_id
# ikea_table.set_next_id(100)
# p macys_table.preview_next_id
# broken_table = Table.new
# p broken_table.serial_num
# class TipCalculator
# @@total_amount
# @@num_people
# @@tip_percent
# def self.something
# end
# end
# tip_calc = TipCalculator.new
# tip_calc.something_else
# class Table
# def a_public_method
# # puts "public"
# a_private_method
# end
# private
# def a_private_method
# puts "private"
# end
# end
# ikea_table = Table.new
# # ikea_table.a_public_method
# # ikea_table.a_private_method
# # ikea_table.initialize
# ikea_table.send :a_private_method
class Bank
def transfer
withdraw
deposit
end
private
def withdraw
end
def deposit
end
end
b = Bank.new
b.transfer
# b.withdraw
# b.deposit
# b.send :withdraw
# class Parent
# def a_public_method(child)
# child.a_protected_method
# end
# protected
# def a_protected_method
# puts "protected"
# end
# end
# class Child < Parent
# end
# class AdoptedChild
# protected
# def a_protected_method
# puts "adopted protected"
# end
# end
# p = Parent.new
# # p.a_protected_method
# c = Child.new
# # c.a_protected_method
# # p.a_public_method(c)
# c.a_public_method(p)
# # ac = AdoptedChild.new
# # p.a_public_method(ac)
# class Parent
# def whoami
# puts "I'm a parent!"
# end
# end
# class Child < Parent
# def whoami
# puts "I'm a child"
# end
# end
# c = Child.new
# c.whoami
# p Child.ancestors
# class Person
# def speak
# "I'm a person"
# end
# end
# class Child < Person
# def speak
# some_good_ideas = super
# some_good_ideas + " who is a child"
# end
# end
# puts Child.new.speak
# p = Person.new
# puts p.speak
# c = Child.new
# puts c.speak
# class Parent
# protected
# def family_secret
# puts "Shhh!"
# end
# end
# class Child < Parent
# def expose_secrets
# family_secret
# end
# def chat(other_person)
# other_person.family_secret
# end
# end
# class Stranger
# def chat(other_person)
# other_person.send :family_secret
# end
# end
# # c.expose_secrets
# # c.send :family_secret
# jo = Child.new
# juha = Child.new
# jo.chat(juha)
# juha.chat(jo)
# skeev = Stranger.new
# skeev.chat(jo)
# skeev.chat(juha)
# jo.chat(skeev)
# class Parent
# def speak(arg)
# puts arg
# end
# end
# class Child < Parent
# def speak
# super("goo goo ga ga")
# end
# end
# c = Child.new
# c.speak
# class Parent
# def speak(arg)
# puts arg
# end
# end
# class Child < Parent
# def speak2
# speak "I'm a child"
# end
# def brand_new_feature
# speak
# speak2
# end
# end
# c = Child.new
# c.speak2
# c.speak("hi")
# class Parent
# def speak
# "hello"
# end
# end
# class Child < Parent
# def speak(arg1, arg2, arg3)
# some_good_idea = super() #super(arg1, arg2, arg3)
# "gibberish #{some_good_idea} gibberish"
# end
# end
# c = Child.new
# puts c.speak([], [], [])
# class Table
# attr_accessor :num_legs
# def initialize(num_legs)
# raise "Boom!"
# if num_legs > 0
# @num_legs = num_legs
# else
# raise "Invalid number of legs"
# end
# end
# end
# t = Table.new(4)
# t = Table.new(-2)
# puts "Hello world!"
# # p t.num_legs
# def add_two(number)
# if not number.respond_to? :+
# raise ArgumentError, "invalid argument"
# elsif number == 0
# raise "I just don't like 0"
# end
# number + 2
# end
# p add_two(1)
# # p add_two({})
# begin
# p add_two(0)
# rescue ArgumentError => e
# puts "You: #{e.message}. Me: Sorry! My bad!"
# rescue => e
# puts "What?!"
# puts e.backtrace
# end
# puts "Hello world!"
# def a
# b
# end
# def b
# # begin
# # c
# # rescue
# # puts "Saved b from crashing"
# # end
# c # rescue puts "Saved b from crashing"
# end
# def c
# d
# end
# def d
# raise "i/o error"
# end
# a
# begin
# exit
# rescue # defaults to StandardError
# puts "Nope!"
# end
# catch :ball do
# 0.upto(10).each do |i|
# puts i
# 10.downto(0).each do |j|
# puts j
# 0.upto(10).each do |k|
# puts k
# # throw :ball if k.zero?
# end
# end
# end
# end
# def find_something
# 0.upto(10).each do |i|
# puts i
# 10.downto(0).each do |j|
# puts j
# 0.upto(10).each do |k|
# return k
# end
# end
# end
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment