Skip to content

Instantly share code, notes, and snippets.

@da3mon
Created September 18, 2010 00:13
Show Gist options
  • Save da3mon/585179 to your computer and use it in GitHub Desktop.
Save da3mon/585179 to your computer and use it in GitHub Desktop.
module Enumerable
def exactly?(percentage, &block)
matching(percentage, &block) == percentage.to_f
end
def more?(percentage, &block)
matching(percentage, &block) >= percentage.to_f
end
def less?(percentage, &block)
matching(percentage, &block) <= percentage.to_f
end
def fuzzy?(percentage, delta=0.0, &block)
matching = matching(percentage, &block)
range = ((percentage - delta)..(percentage + delta))
range.include?(matching)
end
def matching(percentage, &block)
(select(&block).size.to_f / self.size * 100)
end
end
require 'rspec'
require_relative '../../lib/enumerable'
describe Enumerable do
let(:array) { [1, 2, 3, 4, 5] }
describe "#exactly?" do
it "is true when the predicate matches the given percent" do
array.should be_exactly(20) {|x| x <= 1}
end
it "is false when the predicate does not match the given percent" do
array.should_not be_exactly(30) {|x| x <= 1}
end
end
describe "#more?" do
it "is true when the predicate matches the given percent" do
array.should be_more(10) {|x| x <= 1}
end
it "is false when the predicate does not match the given percent" do
array.should_not be_more(30) {|x| x <= 1}
end
end
describe "#less?" do
it "is true when the predicate matches the given percent" do
array.should be_less(30) {|x| x <= 1}
end
it "is false when the predicate does not match the given percent" do
array.should_not be_less(10) {|x| x <= 1}
end
end
describe "#fuzzy?" do
it "is true when the predicate matches the given percentage range" do
array.should be_fuzzy(17, 5) {|x| x <= 1}
end
it "is false when the predicate does not match the given percentage range" do
array.should_not be_fuzzy(10, 1) {|x| x <= 1}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment