Skip to content

Instantly share code, notes, and snippets.

@xaviershay
Created December 4, 2011 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xaviershay/1431560 to your computer and use it in GitHub Desktop.
Save xaviershay/1431560 to your computer and use it in GitHub Desktop.
Ruby puzzle
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
@alindeman
Copy link

Fail, never mind. For some reason the specs are running green all the time. Misconfiguration on my part ...

@floere
Copy link

floere commented Dec 4, 2011

def transform_hash(hash)
  hash.values.transpose
end

:)

@alindeman
Copy link

Yep .. nice.

@josevalim
Copy link

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

@josevalim
Copy link

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