Subscribe to Stuck in an Infiniteloop        RSS Feed
-----

A Late Night Ruby Snippet

Icon 2 Comments
You ever run across a problem that you just say, "why?" And then you had to write a quick snippet to solve it?

This was mine as I was doing my near midnight DIC browsing. [Hey ooooo!]

Behold, a solution!

str = "aaabbbcbbaaa"
pairs = []
counter = 1
(0..(str.length-1)).each do |i|
  if not str[i] == str[i+1]
    pairs << [ str[i], counter ]
    counter = 1
  else
    counter = counter + 1
  end
end

print pairs



Quote

$ ruby encode.rb
[["a", 3], ["b", 3], ["c", 1], ["b", 2], ["a", 3]]

2 Comments On This Entry

Page 1 of 1

Lemur Icon

04 May 2013 - 12:49 AM
http://www.ruby-doc....Enumerable.html

Enumerable has a number of methods that work quite well to simplify problems of this and similar natures. Inject is especially amazing.
1

KYA Icon

05 May 2013 - 11:41 AM
Looking at the doc for inject, I'm not entirely sure if it would be helpful in this regard. You need to be aware of the next element in the sequence which inject doesn't appear to allow unless you let the block be aware of the string globally.
0
Page 1 of 1

August 2014

S M T W T F S
     12
3456789
10111213141516
171819202122 23
24252627282930
31      

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    0 user(s) viewing

    0 Guests
    0 member(s)
    0 anonymous member(s)