0

I have an array like this

[["ContactCreate", "PolicyCreate"], ["Page_1", "Page_3"], ["Page_2"]]

I want to transpose this array, But If I transpose this array, this says

Uncaught exception: element size differs (1 should be 2)

Now I have array with various sizes like this, Is there anyway I can fill fill nil in the size of the greater array and then I can transpose ? Like

[["ContactCreate", "PolicyCreate"], ["Page_1", "Page_3"], ["Page_2",nil]]

If

 [["ContactCreate", "PolicyCreate","contactCreate], ["Page_1", "Page_3"], ["Page_2"]]

then it has to be

 [["ContactCreate", "PolicyCreate","contactCreate], ["Page_1", "Page_3",nil], ["Page_2",nil,nil]]
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29
  • Maybe you can equeue `nil` to small elements before. Or https://stackoverflow.com/questions/26016632/how-can-i-transpose-different-sized-ruby-arrays – iGian Sep 30 '18 at 16:27
  • @iGian That perfectly answers my question, once you have this reply, I will delete my question. Thanks. – Rajagopalan Sep 30 '18 at 16:53
  • The linked question assumes the subarrays are ordered largest to smallest. If that is not necessarily the case you could do the following. n = arr.map(&:size).max; arr.map { |a| Array.new( n) { |i| a[i] } }.transpose #=> [["ContactCreate", "Page_1", "Page_2"], ["PolicyCreate", "Page_3", nil]]`. – Cary Swoveland Sep 30 '18 at 17:37
  • @CarySwoveland No, it works for all the cases, for an example, look a this one,here second array is bigger, it works and gave the right result `[["ContactCreate", "Page_1", "Page_2", nil], ["PolicyCreate", "Page_3", "Page_4", "Page_5"]]` – Rajagopalan Sep 30 '18 at 17:41
  • The two arrays in your example both have four elements. If `arr = [["Page_2"], ["ContactCreate", "PolicyCreate"], ["Page_1", "Page_3"]]`, @Stefan's (accepted) answer at that link yields `arr[0].zip(*arr[1..-1]) #=> [["Page_2", "ContactCreate", "Page_1"]]`. – Cary Swoveland Sep 30 '18 at 18:00
  • I missed @sawa's (excellent) answer to the earlier question, which does not rely on the ordering by size of the subarrays. So yes, sawa has answered your question. – Cary Swoveland Sep 30 '18 at 18:34
  • @CarySwoveland Stefan's answer works fine for me. – Rajagopalan Sep 30 '18 at 18:35
  • That's fine, as long as you understand that it requires the first subarray to be the largest subarray. – Cary Swoveland Sep 30 '18 at 18:42
  • @CarySwoveland I am saying first Sub Array need not to be the largest array. It still works fine. – Rajagopalan Sep 30 '18 at 18:45
  • I showed in my comment above that begins "The two arrays..." that @Stefan's answer only works when the first subarray is the largest. In fact, he makes that clear in his answer. – Cary Swoveland Sep 30 '18 at 19:13

0 Answers0