RosettaCodeData/Task/Run-length-encoding/Ruby/run-length-encoding-3.rb

12 lines
278 B
Ruby
Raw Permalink Normal View History

2015-11-18 06:14:39 +00:00
def encode(string)
string.scan(/(.)(\1*)/).inject("") do |encoding, (char, repeat)|
encoding << (1 + repeat.length).to_s << char
end
2013-04-10 23:57:08 -07:00
end
2015-11-18 06:14:39 +00:00
def decode(string)
string.scan(/(\d+)(\D)/).inject("") do |decoding, (length, char)|
decoding << char * length.to_i
end
2013-04-10 23:57:08 -07:00
end