<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: subarray code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 25 Jul 2008 06:33:56 GMT</pubDate>
    <description>DZone Snippets: subarray code</description>
    <item>
      <title>Extracting all subarray indices from a multi-dimensional array</title>
      <link>http://snippets.dzone.com/posts/show/1956</link>
      <description>Note the use of Array#fetch to define return values for missing indices!&lt;br /&gt;Example: ar = []; x = ar.fetch(5, [])  returns an empty array for non-existing index 5.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;br /&gt;class Array&lt;br /&gt;&lt;br /&gt;   def subar_indices(ar=[], temp=[])&lt;br /&gt;      temp = temp.dup&lt;br /&gt;      self.each_with_index { |item, index| &lt;br /&gt;         if item.class == Array&lt;br /&gt;            temp &lt;&lt; index&lt;br /&gt;            ar &lt;&lt; temp&lt;br /&gt;            ar = item.subar_indices(ar, temp)&lt;br /&gt;         end&lt;br /&gt;      }&lt;br /&gt;      ar.uniq&lt;br /&gt;   end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   def extract_subar_indices&lt;br /&gt;      subarray_indices = self.subar_indices  # subarray_indices is a two-dimensional array&lt;br /&gt;      # puts subarray_indices.inspect&lt;br /&gt;      &lt;br /&gt;      return subarray_indices if subarray_indices.empty?&lt;br /&gt;&lt;br /&gt;      first_subar = subarray_indices.shift   # the first subarray contains all two-dimensional subarray indices                &lt;br /&gt;&lt;br /&gt;      subarray_indices.each do |subar|&lt;br /&gt;         subar_size = subar.size&lt;br /&gt;         str = ""&lt;br /&gt;         count = -1&lt;br /&gt;         (subar_size - 1).times { count += 1; str &lt;&lt; ".fetch(subar[#{count}], [])" }&lt;br /&gt;         str &lt;&lt; ".fetch(subar[#{count + 1}], {}"&lt;br /&gt;         str = "self" &lt;&lt; str&lt;br /&gt;         if eval(str).class == Hash then subar.shift; redo end&lt;br /&gt;      end&lt;br /&gt;&lt;br /&gt;      first_subar.reverse.each do |item| subarray_indices.unshift([item]) end&lt;br /&gt;      subarray_indices&lt;br /&gt;   end&lt;br /&gt;&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;array = [1, 2, [3, 4, [5, 6]], 7, 8, [9]]&lt;br /&gt;&lt;br /&gt;indices = array.extract_subar_indices&lt;br /&gt;&lt;br /&gt;puts indices.inspect  # [[2], [5], [2, 2]]&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sat, 22 Apr 2006 20:14:52 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1956</guid>
      <author>ntk ()</author>
    </item>
  </channel>
</rss>
