Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Generate short URLs using Ruby

This Ruby code generates shortened URLs. It has the added feature that it will not allow words to be created accidentally eg. swear words.

#!/usr/bin/ruby

class ShortUrl
  def initialize()
    @chars = ('a'..'z').to_a + ('1'..'9').to_a + ('A'..'Z').to_a
    @array_size = @chars.size
    @h = Hash.new
    @chars.each {|c| @h[c] = '0'}
    vowels = %w(a e i o u A E I O U 4 3 1 0)
    vowels.each {|v| @h[v] = '1'}
    nums = %w(2 5 6 7 8 9)
    nums.each {|n| @h[n] = '2'}
    @count = 0
    @a = Array.new(7, -1)
    @k = 0
  end 

  def iterate_chars(array_size)
    (0..array_size).each {|i| 
      increment_index(@k)
      convert_to_chars()
    }
  end
  
  def convert_to_chars()
    buffer = ''
    @a.each {|i|
      buffer << @chars[i] if i >= 0
    }
    a = buffer.reverse.scan(/./)
    k = a.length  
    if  (k > 1)  
      if ((@h[a[k-2]] + @h[a[k-1]]) != '10')
        puts buffer.reverse 
      end
    else
      puts buffer.reverse
    end
  end

  def get_short_url(count)
    if count >  @array_size
      new_count = count - @array_size
      iterate_chars(@array_size)
      get_short_url(new_count)
    else
      iterate_chars(count)
    end
  end
  
  def increment_a(i)
    if @a[i] < @array_size - 1
      @a[i] = @a[i] + 1
      return i 
    else
      @a[i] = 0
      return i += 1
    end 
  end

  def increment_index(k)
    old_k = k
    k = increment_a(k)
    
    if k != old_k
      increment_index(k)
    else
      k = 0
    end
    k
  end

end

if __FILE__ == $0
  su = ShortUrl.new  
  su.get_short_url(222761)
end


Note: You will most likely see the " `convert_to_chars': stack level too deep (SystemStackError)" error message after around 253950 iterations, I'm presuming this is expected due to the memory constraints of the language. However 253k short urls is enough for linking my website to itself.

Elegant way of shorten a text string

this method shortens a plain text string down to complete words contained in given scope (count)

def shorten (string, count = 30)
	if string.length >= count 
		shortened = string[0, count]
		splitted = shortened.split(/\s/)
		words = splitted.length
		splitted[0, words-1].join(" ") + ' ...'
	else 
		string
	end
end
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS