Skip to content

Instantly share code, notes, and snippets.

@hawx
Created September 16, 2011 17:37
Show Gist options
  • Save hawx/1222641 to your computer and use it in GitHub Desktop.
Save hawx/1222641 to your computer and use it in GitHub Desktop.
Allow methods to use hashes or not as arguments
class Array
def destructure(*arr)
if size == 1 && first.is_a?(Hash)
arr.map {|k| first[k] }
else
self
end
end
end
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