0

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

5
  • What does results = client.get(...) return into results? Is it already an array? It's at least enumerable, since you're doing results.each... Commented Mar 18, 2015 at 16:58
  • 1
    try results.map(&:title) as the last line in place of ...each and array <<... this will return an Array of all titles from results so really it could be 1 line client.get('/subjects', :genre => subject1).map(&:title) will have the same result. The you just store it in a variable a = function(subject1) Commented Mar 18, 2015 at 17:00
  • yes, client.get('...') turn into real results that I limit by choosing a subject in the genre. @lurker Commented Mar 18, 2015 at 17:04
  • ok, i'm going to try it now @engineersmnky Commented Mar 18, 2015 at 17:06
  • results.each { |r| array << r.title } is what you're looking for Commented Mar 18, 2015 at 17:09

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

so to call on the array later i would just put results.map ?
you can save the result to a variable like so response = function(subject1)
1

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

result = function(subject1)

Comments

-2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.