Created
January 9, 2015 17:26
-
-
Save r00k/0b9a095dd3d9b2855e61 to your computer and use it in GitHub Desktop.
Leveling up our inject skills
This file contains hidden or 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
require 'rspec' | |
def sum(numbers) | |
numbers.inject(0) { |sum, number| sum + number } | |
end | |
def product(numbers) | |
numbers.inject(1) { |sum, number| sum * number } | |
end | |
# EASIER: Write product, a method that accepts an | |
# array of numbers, and multiplies them all together. | |
# HARDER: Write a method that accepts an array | |
# of strings. | |
# Return a hash where the keys are the strings | |
# and the values are the length of each string. | |
# | |
# hash_of_lengths(["foo", "ab"]) => | |
# { "foo" => 3, "ab" => 2 } | |
describe "#sum" do | |
it "returns the sum of an array of numbers" do | |
numbers = [1, 2, 3, 4] | |
result = sum(numbers) | |
expect(result).to eq 10 | |
end | |
end | |
def hash_of_lengths(strings) | |
strings.inject({}) { |hsh, string| hsh[string] = string.length ; hsh } | |
end | |
describe "#hash_of_lengths" do | |
it "returns a hash where keys are strings and values are their lengths" do | |
strings = ["a", "bb", "ccc"] | |
result = hash_of_lengths(strings) | |
expect(result).to eq({ "a" => 1, "bb" => 2, "ccc" => 3 }) | |
end | |
end | |
# Harder: Write a method that takes an element and a collection | |
# and returns true if the collection contains only things | |
# that are == to that element. | |
# Easier: do hash_of_lengths | |
# | |
describe "#all_equal" do | |
context "when all elements in collection == argument" do | |
it "returns true" do | |
result = all_equal("foo", ["foo", "foo"]) | |
expect(result).to be_truthy | |
end | |
end | |
context "when all elements are not == to argument" do | |
it "returns false" do | |
result = all_equal("foo", ["foo", "bar"]) | |
expect(result).to be_falsey | |
end | |
end | |
end | |
def all_equal(argument, collection) | |
collection.inject(true) { |result, element| result && element == argument } | |
end | |
count = 0 | |
foos.each do |foo| | |
count += 1 if foo.valid? | |
end | |
count | |
foos.inject(0) { |result, foo| result + 1 if foo.valid? ; result } | |
foos.count { |foo| foo.valid? } | |
results = [] | |
foos.each do |foo| | |
if whatever | |
results << foo | |
end | |
end | |
results | |
foos.inject([]) { |acc, element| acc << element if whatever ; acc } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment