i have question using foreach
loops in ruby.
i want display documents , using foreach
loop in order display these documents. returns error i
variable inside of data["response"]["docs"][i]["topic"]
json string iterating over.
i not understand why is. can tell me doing wrong?
if data["response"]["docs"][0]["topic"]
works fine not i
. why that?
<% (0..10).each |i| %> <%= %> <br/> <%= data["response"]["docs"][i]["topic"] %> <% end %>
my question is, how many items there in data["response"]["docs"]
? there 11? either way use following code instead:
<% data["response"]["docs"].each_with_index |item, index| %> <%= index %> <br/> <%= item["topic"] %> <% end %>
this iterates on data["response"]["docs"]
no matter how many there (whether is 1 doc or 20 docs) , stores value in variable named item
. each_with_index
function gives index well, stored in index
, can display later. if want first 11 use:
<% data["response"]["docs"].first(11).each_with_index |item, index| %>
this grab maximum of 11 doc items.
Comments
Post a Comment