Search code examples
rubyarraysfunctionstore

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


In ruby, how can I convert a function response into array for later usage?

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

function(subject1)

My code looks like something similar above. My results however are never stored. Please and thanks for your help :)


Solution

  • Each method will iterate through every element whereas map would return an array in itself.

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