Created
December 4, 2011 22:56
-
-
Save xaviershay/1431560 to your computer and use it in GitHub Desktop.
Ruby puzzle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe '#transform_hash' do | |
it 'transforms a single entry hash' do | |
transform_hash(a: [1, 0]).should == [[1], [0]] | |
end | |
it 'transforms a double entry hash' do | |
transform_hash(a: [1, 0], b: [0, 1]).should == [[1, 0], [0, 1]] | |
end | |
it 'transforms a multiple entry hash' do | |
transform_hash( | |
a: [1, 0], | |
b: [0, 1], | |
c: [1, 1] | |
).should == [[1, 0, 1], [0, 1, 1]] | |
end | |
end | |
def identity_stream(value) | |
Enumerator.new do |yielder| | |
while true | |
yielder.yield(value) | |
end | |
end | |
end | |
def transform_hash(hash) | |
hash.values.reverse.reduce(identity_stream([])) {|x, y| | |
y.zip(x).map(&:flatten) | |
} | |
end |
def transform_hash(hash)
hash.values.transpose
end
:)
Yep .. nice.
Maybe try the simplest approach possible? (I haven't tried if it really works)
def transform_hash(hash)
x, y = [], []
hash.values.each do |i, j|
x << i
y << j
end
[x,y]
end
Ah, love the transpose one. Killer. :D
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fail, never mind. For some reason the specs are running green all the time. Misconfiguration on my part ...