在 ruby 中,如何将函数的 response/results 转换为数组?

In ruby, how can I convert a function's response/results into an array?

在ruby中,如何将函数响应转换为数组供以后使用?

array = []
def function (subject1)
    results = client.get('/subjects', :genre => subject1)
    results.each { |r| puts r.title }
    array << r.title
end

function(subject1)

我的代码与上面类似。然而,我的结果永远不会被存储。请并感谢您的帮助:)

每个方法都会遍历每个元素,而 map 本身会 return 一个数组。

def function(subject1)
    results = client.get('/subjects', :genre => subject1)
    results.map { |r| r.title }
end

function(subject1)

"My results however are never stored" - 然后存储结果:

result = function(subject1)

或者你可以让数组成为一个全局变量

$array = []
def function (subject1)
  results = client.get('/subjects', :genre => subject1)
  results.each { |r| $array << r.title }
end

function(subject1)

或者您可以这样做

array = []
def function (subject1)
  results = client.get('/subjects', :genre => subject1)
  results.each { |r| puts r.title }
end

array = function(subject1)