2 Replies - 687 Views - Last Post: 28 January 2014 - 08:46 PM Rate Topic: -----

#1 heaphyg  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 85
  • Joined: 30-August 13

nested array?

Posted 28 January 2014 - 07:37 PM

I am trying to collect the first element who's value does not equal its index plus 1 (4 in this case). When I inspect my collector array it seems to turn into a nested array (which confuses me). In addition when I pop the last value from collector array I expect to just get 5 but I get both 5 and 4 which also confuses confuses me.

a = [1,2,4,5] 
a.each_with_index do |x,i| 
  collector = [] 
  if x != i + 1
    collector << x
  end
    puts collector.inspect    ## collector is a nested array. not sure why.
end



Is This A Good Question/Topic? 0
  • +

Replies To: nested array?

#2 andrewsw  Icon User is offline

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3458
  • View blog
  • Posts: 11,707
  • Joined: 12-December 12

Re: nested array?

Posted 28 January 2014 - 07:49 PM

It is not a nested array, you are redeclaring collector each time, and printing it, within the loop. I assume you want to collect all the matched values into a single array:
a = [1,2,4,5]
collector = []
a.each_with_index do |x,i| 
  if x != i + 1
    collector << x
  end
end
puts collector.inspect    ## [4, 5]

Was This Post Helpful? 1
  • +
  • -

#3 Lemur  Icon User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1359
  • View blog
  • Posts: 3,425
  • Joined: 28-November 09

Re: nested array?

Posted 28 January 2014 - 08:46 PM

If you're trying to play missing number, there's an easier way to do it.

sorted_array = array.sort
(sorted_array.first..sorted_array.last).reduce(:+) - array.reduce(:+)



...and the result:
array = [1,2,4,5,6]
=> [1, 2, 4, 5, 6]
[29] pry(main)> sorted_array = array.sort # If the array is in random order
=> [1, 2, 4, 5, 6]
[30] pry(main)> (sorted_array.first..sorted_array.last).reduce(:+) - array.reduce(:+)
=> 3



You're making the problem far harder than it needs to be.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1