【问题标题】:Ruby + recursive function + defining global variableRuby + 递归函数 + 定义全局变量
【发布时间】:2015-02-27 09:27:43
【问题描述】:

我正在使用 Ruby 提取 bitbucket 存储库列表。来自 bitbucket 的响应将仅包含 10 个存储库和一个标记,用于下一页将有另外 10 个存储库等等......(他们称之为分页)

所以,我编写了一个递归函数,如果存在下一页标记,它会调用自身。这将持续到最后一页。

这是我的代码:

#!/usr/local/bin/ruby
require 'net/http'
require 'json'
require 'awesome_print'

@repos = Array.new

def recursive(url)

    ### here goes my net/http code which connects to bitbucket and pulls back the response in a JSON as request.body 
    ### hence, removing this code for brevity

    hash = JSON.parse(response.body)

    hash["values"].each do |x|
        @repos << x["links"]["self"]["href"]
    end

    if hash["next"]
        puts "next page exists"
        puts "calling recusrisve with: #{hash["next"]}"
        recursive(hash["next"])
    else
        puts "this is the last page. No more recursions"
    end
end

repo_list = recursive('https://my_bitbucket_url')
@repos.each {|x| puts x}

现在,我的代码工作正常,它列出了所有的 repos。

问题: 我是 Ruby 新手,所以我不确定我使用上面的全局变量 @repos = Array.new 的方式。如果我在函数中定义数组,那么每次调用函数都会创建一个新数组,覆盖之前调用的内容。

那么,在这种情况下,Ruby 程序员如何使用全局符号。我的代码是否遵守 Ruby 道德规范,或者它是一种非常业余的(但正确,因为它有效)的方式。

【问题讨论】:

标签: ruby recursion


【解决方案1】:

共识是尽量避免全局变量。

我会像这样递归地构建集合:

def recursive(url)
  ### ...

  result = [] 

  hash["values"].each do |x|
    result << x["links"]["self"]["href"]
  end

  if hash["next"]
    result += recursive(hash["next"])
  end
  result
end

或将集合交给函数:

def recursive(url, result = [])
  ### ...

  hash["values"].each do |x|
    result << x["links"]["self"]["href"]
  end

  if hash["next"]
    recursive(hash["next"], result)
  end
  result
end

无论哪种方式都可以调用函数

repo_list = recursive(url)

我会这样写:

def recursive(url)
  # ...

  result = hash["values"].map { |x| x["links"]["self"]["href"] }
  result += recursive(hash["next"]) if hash["next"]
  result
end

【讨论】:

  • += 方法我从未用于数组。所以没有意识到这一点。我认为这正是我所需要的。我从一开始就知道我定义变量的方式看起来不太好。感谢您的时间和回答。我将采用第二种方法def recursive(url, result = [])。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-12
  • 1970-01-01
  • 2020-07-29
  • 2022-01-07
  • 2015-04-23
  • 2012-11-06
  • 2015-03-08
相关资源
最近更新 更多