• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to "flatten" a Ruby array

 
Ranch Hand
Posts: 1296
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok so I'm trying to learn Ruby. My plan was to get a feel for the syntax by trying to work through Ninety-Nine Lisp Problems in Ruby. However I got stuck on Problem 7.


My test code looks like:


And my "my_flatten" method looks like:

But my code fails at my first assertion (Expected [] but was [[]]),

and if I comment that out it fails on my third assertion too:

Expected [1, 2, 3, 4, 5] but was [1, [2, 3], 4, 5].

Can any of you guys give me a nudge int the right direction?
[ February 18, 2008: Message edited by: Garrett Rowe ]
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It looks like your my_flatten will create a new array every time it's invoked - that's the first line, after all. But is that really what you want? A flattened array should have just one array, no matter how many times the method recurses, yes? In many cases you want to append new elements to an existing array, not create a new one. Can you think of a way to do that?
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This recursive code below will pass all your tests:

def flatten_array(arr)
 narr = Array.new
 arr.each do |elem|
   if (elem.class == 'Array') then
     narr.push(flatten_array(elem))
   else
     narr.push(elem)
   end
 end
 narr
end

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic