【发布时间】: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 道德规范,或者它是一种非常业余的(但正确,因为它有效)的方式。
【问题讨论】:
-
一个全局变量被定义为前缀
$。@标记当前对象的类实例变量。 -
这个问题可能对stackoverflow.com/questions/1042384/…有帮助