Skip to content

Instantly share code, notes, and snippets.

@bravoecho
Last active December 26, 2015 14:48
Show Gist options
  • Save bravoecho/7167954 to your computer and use it in GitHub Desktop.
Save bravoecho/7167954 to your computer and use it in GitHub Desktop.
module Refines
refine Array do
def strictly_increasing?
each_cons(2).all? {|x, y| x < y }
end
end
refine String do
def char_indexes
each_char
.with_index
.with_object(Hash.new { |h, k| h[k] = [] }) { |(char, idx), hsh|
hsh[char] << idx
}
end
end
end
using Refines
def letter_match(target, str)
first_set, *rest = target.char_indexes.values_at(*str.split(//))
first_set.product(*rest).select { |arr| arr.strictly_increasing? }
end
describe "letter_match" do
let(:a) { "hello world" }
specify "single match" do
expect(letter_match(a, "e")).to eq [[1]]
end
specify "single letter with multiple matches" do
expect(letter_match(a, "l")).to eq [[2],[3],[9]]
end
specify "multiple matches, example 1" do
expect(letter_match(a, "el")).to eq [[1,2], [1,3], [1,9]]
end
specify "multiple matches, example 2" do
expect(letter_match(a, "lo")).to eq [[2,4], [2,7], [3,4], [3,7]]
end
specify "multiple matches, example 3" do
expect(letter_match(a, "lod")).to eq [[2,4,10], [2,7,10], [3,4,10], [3,7,10]]
end
end
# $ rspec ordered_matches_lrug.rb
# /home/luca/Dropbox/snippets/ordered_matches_lrug.rb:2: warning: Refinements are experimental, and the behavior may change in future versions of Ruby!
# .....
#
# Finished in 0.00109 seconds
# 5 examples, 0 failures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment