marriedjane875
marriedjane875

Reputation: 673

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

Upvotes: 0

Views: 296

Answers (3)

Duck1337
Duck1337

Reputation: 524

Or you can make array a global var

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

function(subject1)

Or you can do this

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

array = function(subject1)

Upvotes: -2

steenslag
steenslag

Reputation: 80065

"My results however are never stored" - store the result then:

result = function(subject1)

Upvotes: 1

coderhs
coderhs

Reputation: 4837

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)

Upvotes: 2

Related Questions