Topic: testing the next item in a each do block

I am dynamically creating a navigation menu in a helper. It gathers all the pages associated with a website and then I run an each do |page|. What I need to know is how to test to see if the next item in the collection is a child of it. Here's what I have...

def pageNav(website)
  @li_list=""
  @page_list = pageList(website)
  @page_list.each do |p|
    if (p.indexed == true)
  if (p[+1].child == false) //this is the part I don't know about, how to access the next p
    @li = "<li><a href=\"/"<< p.ptitle.gsub(/\s+/, "") << ".html\" << p.ptitle<< "</a></li>"
    @li_list<<@li
  else
    @li = "<li><a href=\"/"<< p.ptitle.gsub(/\s+/, "") << ".html\">" << p.ptitle << "</a>"
          @li = "<ul><li><a href=\"/"<<p[+1].ptitle.gsub(/\s+/, "") << ".html\">" << p.ptitle << "</a></li></ul></li>"
    @li_list<<@li
  end
  end 
end
    
    return @li_list.html_safe
  end

Re: testing the next item in a each do block

....
What I need to know is how to test to see if the next item in the collection is a child of it
...

What you get is an Array, no matter which kind of object you have inside, it will never have the 'child' method', except if you 'override' it with open class technique yourself.

Second point, in Ruby no need to check an object to true, you can just omit it:

#your code
if (p.indexed == true)
..
#shorter and more Rubyish:
if p.indexed

By the way there is no 'indexed' method either in Array class, you can use 'first' method available in Enumerable and Array classes. Or 'next' method from Enumerator class.
See Ruby API for more details: http://ruby-doc.org/core-1.9.3/Enumerat … hod-i-next

See also 'next_element' method from Rails API in HTML::Selector class, http://api.rubyonrails.org/

Last edited by Javix (2012-07-11 11:20:06)