Created
September 16, 2011 17:37
-
-
Save hawx/1222641 to your computer and use it in GitHub Desktop.
Allow methods to use hashes or not as arguments
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
class Array | |
def destructure(*arr) | |
if size == 1 && first.is_a?(Hash) | |
arr.map {|k| first[k] } | |
else | |
self | |
end | |
end | |
end |
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
require_relative 'destructure' | |
require 'minitest/autorun' | |
class DestructureTest < MiniTest::Unit::TestCase | |
def test_can_pull_values_from_hash | |
args = [{:a => 1, :b => 2, :c => 3}] | |
assert_equal [1, 2, 3], args.destructure(:a, :b, :c) | |
end | |
def test_can_assign_positions_to_array | |
args = [1, 2, 3] | |
assert_equal [1, 2, 3], args.destructure(:a, :b, :c) | |
end | |
end | |
# def test(*args) | |
# a, b, c = args.destructure(:a, :b, :c) | |
# print a, b, c, "\n" | |
# end | |
# | |
# test 1, 2, 3 | |
# #=> 123 | |
# test b: 2, c: 3, a: 1 | |
# #=> 123 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment