从 PHP 切换到 Rails 需要帮助翻译 URL 缩短器

发布于 2024-11-03 07:10:00 字数 606 浏览 3 评论 0原文

以前的开发人员使用此网站中的源代码来创建URL 缩短器。我的主要任务是将这段代码翻译成 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;
}

我是 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 :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌生 2024-11-10 07:10:00

这基本上相当于 PHP 代码的直接移植。

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

代码和非常基本的测试结果(以确保功能相同)可以在 https:// gist.github.com/941152

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文