Created
June 12, 2013 03:46
-
-
Save hlxwell/5762695 to your computer and use it in GitHub Desktop.
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 "rubygems" | |
require "rspec" | |
class String | |
def syllable | |
# bl|qu|ng|ch|rt| | |
consonants = "bcdfghjklmnpqrstvwxzh" | |
vowels = "aeiouy" | |
word = self.downcase | |
parts = word.split(/(?=ly)/) | |
parts = parts.first.split(/(?=ed)/) + parts[1..-1] | |
parts = parts.first.split(/(?=[^i]al)/) + parts[1..-1] | |
parts = parts.first.split(/(?=[#{consonants}])/) + parts[1..-1] | |
##### process 1 | |
parts = parts.inject([]) do |result, part| | |
# [pa r ti al] => par, tial | |
if result.size > 0 and part.size == 1 and part =~ /[#{consonants}]/ | |
result[-1] = "#{result.last}#{part}" | |
else | |
result.push part | |
end | |
result | |
end | |
##### process 2 | |
# ["syl", "lab", "le"] => ["syl", "la", "ble"] | |
parts = parts.inject([]) do |result, part| | |
# |qu|ng|ch|rt | |
if result.size > 0 and "#{result.last[-1]}#{part[0]}" =~ /bl/ | |
part = "#{result.last[-1]}#{part}" | |
result[-1] = result.last[0..-2] | |
end | |
result.push part | |
result | |
end | |
##### process 3 | |
# Concate the first one to seconds | |
if parts.first !~ /[#{consonants}]+[#{vowels}]+/ | |
["#{parts[0]}#{parts[1]}", parts[2..-1]].flatten | |
else | |
parts | |
end | |
end | |
end | |
describe "String Syllables" do | |
it "should be correct" do | |
{ | |
surreptitious: %w{sur rep ti tious}, | |
successfully: %w{suc cess ful ly}, | |
processed: %w{pro cess ed}, | |
consonants: %w{con so nants}, | |
syllable: %w{syl la ble}, | |
china: %w{chi na}, | |
great: %w{great}, | |
threat: %w{threat}, | |
translationally: %w{trans la tion al ly}, | |
partial: %w{par tial}, | |
level: %w{lev el}, | |
usual: %w{us u al} | |
}.each do |k, v| | |
puts k.to_s.syllable.inspect | |
# k.to_s.syllable.should == v | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment