开发者

Switching from PHP to Rails Need Help translating URL shortener

开发者 https://www.devze.com 2023-02-28 20:28 出处:网络
Previous developers used source code from this website to create a URL shortener. I am essentially tasked with translating this piece of code into ruby:

Previous developers used source code from this website to create a URL shortener. I am essentially tasked with translating this piece of code into ruby:

function getIDFromShortenedURL1 ($string, $base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
    $length = strlen($base);
    $size = strlen($string) - 1;
    $string = str_split($string);

    $out = strpos($base, array_pop($string));

    foreach($string as $i => $char)
    {
       开发者_开发百科 $out += strpos($base, $char) * pow($length, $size - $i);
    }
    return $out;
}

I am new to ruby and any help would be much appreciated :)


Here's what basically amounts to a direct port of the PHP code.

def getIDFromShortenedURL1(string, base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
  length = base.length         # $length = strlen($base);
  size   = string.length - 1   # $size   = strlen($string) - 1;
  string = string.split ''     # $string = str_split($string);

  out = base.index string.pop  # $out = strpos($base, array_pop($string));

  string.each_with_index do |char, i|  # foreach($string as $i => $char);
    # $out += strpos($base, $char) * pow($length, $size - $i);
    out << base.index(char) * (length ** (size - i))
  end
  out # return $out;
end

The code an the results of a very basic test (to make sure the functionality is equal) can be found at https://gist.github.com/941152.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号