[RCR] Array#transpose way of dealing with nil's

S

Simon Strandgaard

At the moment #transpose rejects nil values.
It could be really nice if one tell #transpose that it
whenever it meets a nil entry.. that a nil value also should be outputted.

[[1, 2], [3, 4], nil, [5, 6]].transpose(true)
#=> [[1, 3, nil, 5], [2, 4, nil, 6]]


I often find myself needing this for unittesting.. like this

def generic_test_bracket_matcher(str, inpos, expected_xs, expected_ys)
res = inpos.map {|p| str.match_bracket(p) }
ys, xs = res.transpose # BOOM: this doesn't like nil elements
assert_equal(expected_xs, xs)
assert_equal(expected_ys, ys)
end
 
S

Simon Strandgaard

At the moment #transpose rejects nil values.
It could be really nice if one tell #transpose that it
whenever it meets a nil entry.. that a nil value also should be outputted.

[[1, 2], [3, 4], nil, [5, 6]].transpose(true)
#=> [[1, 3, nil, 5], [2, 4, nil, 6]]


I often find myself needing this for unittesting.. like this

def generic_test_bracket_matcher(str, inpos, expected_xs, expected_ys)
res = inpos.map {|p| str.match_bracket(p) }
ys, xs = res.transpose # BOOM: this doesn't like nil elements
assert_equal(expected_xs, xs)
assert_equal(expected_ys, ys)
end

here is a possible implementation

bash-2.05b$ ruby test_transpose.rb
Loaded suite test_transpose
Started
...
Finished in 0.004324 seconds.

3 tests, 3 assertions, 0 failures, 0 errors
bash-2.05b$ expand -t2 test_transpose.rb
require 'test/unit'

class Array
def transpose_except(*elements_to_exclude)
n = 0
self.each do |i|
n = [n, i.size].max if i.kind_of?(Array)
end
ary = self.map do |i|
next *n if elements_to_exclude.member?(i)
i
end
ary.transpose
end
end

class TestTranspose < Test::Unit::TestCase
def test_trans1
ary = [[1, 2], [3, 4], [5, 6]]
assert_equal([[1, 3, 5], [2, 4, 6]],
ary.transpose_except)
end
def test_trans2
ary = [[1, 2], nil, [3, 4]]
assert_equal([[1, nil, 3], [2, nil, 4]],
ary.transpose_except(nil))
end
def test_trans3
ary = [[1, 2], :a, [3, 4], :b, [5, 6]]
assert_equal([[1, :a, 3, :b, 5], [2, :a, 4, :b, 6]],
ary.transpose_except:)a, :b))
end
endbash-2.05b$
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top