Created
August 17, 2008 22:20
-
-
Save sunny/5859 to your computer and use it in GitHub Desktop.
Array#to_h Hash#to_h which can take blocks
This file contains hidden or 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
class Array | |
def to_h(&block) | |
ary = block_given? ? self.collect(&block) : self | |
Hash[*ary.flatten] | |
end | |
end | |
class Hash | |
def to_h(&block) | |
return self if !block_given? | |
Hash[*self.collect(&block).flatten] | |
end | |
end | |
if __FILE__ == $0 | |
require 'test/unit' | |
class ArrayToHashTest < Test::Unit::TestCase | |
HASH = { :bacon => 42, :tasty => 52 } | |
def test_array_to_h | |
result = [[:bacon,42], [:tasty,52]].to_h | |
assert_equal HASH, result | |
end | |
def test_array_to_h_with_block | |
result = [[30, :bacon], [40, :tasty]].to_h { |k, v| [v, k+12] } | |
assert_equal HASH, result | |
end | |
def test_hash_to_h | |
assert_equal HASH, HASH.to_h | |
end | |
def test_hash_to_h_with_block | |
result = ({ 30 => :bacon, 40 => :tasty }).to_h { |k, v| [v, k+12] } | |
assert_equal HASH, result | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment