Best way to `shift` a frozen array?

16 views
Skip to first unread message

Dave Everitt

unread,
Apr 6, 2013, 11:33:09 AM4/6/13
to na...@googlegroups.com
I just came across the fact that nanoc freezes arrays from the YAML metadata in content files, so won't respond to shift etc. I have different length lists of tabs on several pages, only the first of which always needs class="active". Then I want to loop through the remaining array items (omitting the first). I managed this in the layout by using dup to 'shallow copy' the frozen array, then using shift on the array copy as follows:

  <ul class="tabs">

    <li><a class="active" href="#<% t = @item[:tabs].dup; t1 = t.shift %><%= t1 %>"><%= t1 %></a></li>

    <% t.each do | i | %>

    <li><a href="#<%= i %>"><%= i %></a></li>

    <% end %>

  </ul>


YAML example:

tabs:
- tab1
- tab2
- tab3
...

Just wondering if there's a cleaner, DRYer way? I want to hard-code the class into the output - my existing Javascript handles the tabs nicely that way.

Choan Gálvez

unread,
Apr 6, 2013, 12:38:04 PM4/6/13
to na...@googlegroups.com
For the first part, you can just use `item[:tabs].first` to access the
first element.

For the iteration, apply each on a slice: `item[:tabs][0..-1].each`.

Alternatively, you can use `item[:tabs].each_with_index` and use just
one loop.

Best.
--
Choan G�lvez

Ukecosas. Los ukeleles que nos gustan, tambi�n para ti
Vis�tanos: <http://ukecosas.es/>
Deg�stanos en Facebook: <http://facebook.com/ukecosas>


Message has been deleted

Dave Everitt

unread,
Apr 7, 2013, 7:25:38 PM4/7/13
to na...@googlegroups.com
That works! But I ended up with this:

  <ul class="tabs">
    <% @item[:tabs].each do | i | %>
    <li><a <% if i == @item[:tabs][0] %>class="active" <% end %>href="#<%= i %>"><%= i %></a></li>
    <% end %>
  </ul>

as I'm after Ruby 1.8.7 compatibility (and I think .each_with_index needs 1.9) but thanks for the tips :-)

Reply all
Reply to author
Forward
0 new messages