0

I have the following code:

[array1, array2, array3].transpose

I want to do something like this:

[array1, array2, array3].transpose unless array2[value] == ""

I want to transpose each array, but when the value for array2 that is being transposed is blank I want to skip to the next set of values altogether, ensuring that none of the arrays get transposed.

How can I handle that within Ruby 1.9.3?

2
  • Suppose you have [["a","b"], ["", "c"], ["d", "e"]]. On tranpose, do you want the result as ["b", "c", "e"] ? Commented Oct 22, 2013 at 17:56
  • That is correct. ["b", "c", "e"] is the end goal. Commented Oct 22, 2013 at 17:57

2 Answers 2

3

Consider this :

arr1 = ["a", "b"]
arr2 = ["",  "c"]
arr3 = ["d", "e"]

Now, as per your requirement,; you want those tranposed arrays where arr2 blank value is not present.

Use #reject to do that as:

[arr1, arr2, arr3].transpose.reject{ |x| x[1].empty? }

Here, x[1] corresponds to the second element in each transposed array; and it comes from arr2; so here, we rejected all those instances where "" was present in arr2.

Hope it helps

Sign up to request clarification or add additional context in comments.

1 Comment

.reject - That does it. Never cease to be amazed...Thanks for the help.
1

If you had large arrays, and memory were a concern, you could reduce the size of the array before transposing it. That's straightfoward. Here's one way (i being the row containing one or more instances of bad_obj):

def tr(arr, i, bad_obj)
  bad_cols = []
  arr[i].each_with_index {|e,i| bad_cols << i if e==bad_obj}
  arr.map {|row| row.reject.with_index {|e,i| bad_cols.include?(i)}}.transpose
end
arr = [[1,2,3], [4,'',6], [7,8,9]]  
tr(arr, 1, "") # => [[1,4,7], [3,6,9]]
  • construct an array bad_cols that contains the indices of the columns to be skipped.
  • remove the bad_cols columns from each row, then apply transpose.

Edit: replaced

bad_cols = arr[i].each_with_index.reduce([]) {|a,e| a << e.last if e.first==bad_obj; a}

with the first two lines of def tr(). Simpler is better.

1 Comment

It's always helpful and eye-opening to see other methods like this. No doubt this will help in the future - Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.