Skip to content

Instantly share code, notes, and snippets.

@TimLang
Last active August 29, 2015 13:57
Show Gist options
  • Save TimLang/9362738 to your computer and use it in GitHub Desktop.
Save TimLang/9362738 to your computer and use it in GitHub Desktop.
array_custom_splite
class Array
def custom_split &block
tmp = self.each_with_index.inject({}) do |hash, (obj, index)|
if block.call(obj) || (index == 0)
hash[index] = []
else
hash[hash.keys.last] << obj
end
hash
end.map{|h| (h[0] = self[h[0]], h[1]=h[1]).flatten}
tmp.each_with_index do |item, i|
if item.size == 1 && (i< (tmp.size-1)) && block.call(item.first)
tmp[i+1].unshift(item).flatten!
item.pop
end
end.delete([])
tmp
end
end
a = [8,9,8,"muti1", 'muti11', 3,3,3,3,3,'muti2','muti22',4,4,4,4,4]
p a.custom_split{|x| x =~ /[^\d]+/}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment