0

I have a function return_summoner_champion_list(name) that will return the following JSON data when called

[
  {
    "id"=>"1",
    "name"=>"A"
  },
  {
    "id"=>"2",
    "name"=>"B"
  },
  and so on...
]

How do I iterate through the JSON array and print out all ids?

I tried

return_summoner_champion_list(name).each do |list|
  puts list["id"]
end

but it still returns the same JSON data as above without any changes.

1
  • That's not JSON, that's an array of hashes. Iterate through it like you would an array. Commented Jul 16, 2015 at 21:44

2 Answers 2

1

I think you're looking for Array#collect not Array#each:

return_summoner_champion_list(name).collect{|l| l['id']}
=> [1,2, ...]
Sign up to request clarification or add additional context in comments.

Comments

0

Is your method returning JSON or an Ruby array? If it is indeed returning JSON, first convert that to an array with JSON.parse(), and then work with the array that is returned.

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.