Run-length encoding: Difference between revisions

m (toss another unneeded quibble)
Line 3,220:
 
=={{header|Ruby}}==
 
<br>'''Built-in'''<br>
 
Ruby has built-in run-length encoding in the form of <code>chunk</code>, here I provide a thin wrapper around it:
 
<lang ruby>
# run_encode("aaabbbbc") #=> [["a", 3], ["b", 4], ["c", 1]]
def run_encode(string)
string
.chars
.chunk{|i| i}
.map {|kind, array| [kind, array.length]}
end
 
# run_decode([["a", 3], ["b", 4], ["c", 1]]) #=> "aaabbbbc"
def run_decode(char_counts)
char_counts
.map{|char, count| char * count}
.join
end
 
</lang>
 
<lang ruby>def encode(string)
string.scan(/(.)(\1*)/).collect do |char, repeat|
Anonymous user