Last active
August 29, 2015 14:02
-
-
Save ryanholm/ecb23f1d7fc6cbfef198 to your computer and use it in GitHub Desktop.
BLOC Blocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#CP1 | |
def sort_by_length(sort_this_array) | |
sort_this_array.sort { |x,y| x.length <=> y.length} | |
end | |
def filter(filter_this_array) | |
filter_this_array.select { |num| num > 5 } | |
end | |
#RSpec | |
describe "sort_by_length" do | |
it "sorts an array of strings by length" do | |
a = %w(z yyyy xxx ww) | |
sorted = %w(z ww xxx yyyy) | |
sort_by_length(a).should eq(sorted) | |
end | |
it "sorts hashes by length" do | |
a = [{a: "a", b: "b"}, { key: "value"}, {}] | |
sorted = [{}, { key: "value"}, {a: "a", b: "b"}] | |
sort_by_length(a).should eq(sorted) | |
end | |
end | |
describe "filter" do | |
it "returns numbers greater than 5 in a small array" do | |
filter([1, 3, 7, 8]).should eq([7, 8]) | |
end | |
it "returns numbers greater than 5 in a large array" do | |
a = [1, 2, 17, 56, 7, 12, 3, 18, 19, 23] | |
r = [17, 56, 7, 12, 18, 19, 23] | |
filter(a).should eq(r) | |
end | |
end | |
#CP2 | |
def add_two(map_this_array) | |
map_this_array.map { |item| "#{item} + 2 = #{item + 2}" } | |
end | |
#RSpec | |
describe "add_two" do | |
it "adds 2 to each element in an array" do | |
a = [1, 2, 3] | |
r = ["1 + 2 = 3", "2 + 2 = 4", "3 + 2 = 5"] | |
add_two(a).should eq(r) | |
end | |
it "adds 2 to each element in a longer array" do | |
a = [5, 7, 3, 12, 15] | |
r = ["5 + 2 = 7", | |
"7 + 2 = 9", | |
"3 + 2 = 5", | |
"12 + 2 = 14", | |
"15 + 2 = 17"] | |
add_two(a).should eq(r) | |
end | |
end | |
#CP3 | |
class Array | |
def new_map | |
a = [] | |
self.each do |item| | |
a << yield(item) | |
end | |
a | |
end | |
def new_map!(&block) | |
replace_array = self | |
replace_array.replace(self.new_map(&block)) | |
end | |
end | |
#RSpec | |
describe "Array" do | |
describe "new_map" do | |
it "should not call map" do | |
a = [1, 2, 3] | |
a.stub(:map) { '' } | |
a.new_map { |i| i + 1 }.should eq([2, 3, 4]) | |
end | |
it "should map any object" do | |
a = [1, "two", :three] | |
a.new_map { |i| i.class }.should eq([Fixnum, String, Symbol]) | |
end | |
end | |
describe "new_map!" do | |
it "should change the array" do | |
a = [1, 2, 3] | |
a.new_map! { |i| i + 1 } | |
a.should eq([2, 3, 4]) | |
end | |
it "should change the array for classes" do | |
a = [1, "two", :three] | |
a.new_map! { |i| i.class } | |
a.should eq([Fixnum, String, Symbol]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment