Skip to content

Instantly share code, notes, and snippets.

@michaelfeathers
Created July 24, 2015 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelfeathers/037b4785425a86b23efa to your computer and use it in GitHub Desktop.
Save michaelfeathers/037b4785425a86b23efa to your computer and use it in GitHub Desktop.
class Array
def prefixes
result = []
(0..size).each {|n| result << take(n) }
result
end
def indices value
map {|v| v == value ? 0 : 1 }
end
def negate
map {|v| v == 0 ? 1 : 0 }
end
def times ary
result = []
each_with_index { |v,n| result << v * ary[n] }
result
end
def plus n
map {|v| v + n }
end
def group_on mask
return [] if size != mask.size
groups = {}
mask.each_with_index do |v,n|
(groups[v] ||= []) << self[n]
end
groups.values
end
end
class String
def to_a; chars.to_a; end
end
def words text
rep = ' ' + text
letters_mask = rep.to_a.indices(' ')
spaces_mask = letters_mask.negate
keys_mask = letters_mask.times(spaces_mask.prefixes.map {|v| v.reduce(0,:+) }.plus(1))
rep.to_a.group_on(keys_mask).drop(1).map(&:join)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment