Created
June 21, 2010 08:29
-
-
Save sergeych/446581 to your computer and use it in GitHub Desktop.
Python-inspired Hash extension: index sequence getters/setters
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
# Python-inspired Hash extension: index sequence getters/setters | |
# author:: [email protected] | |
# | |
# Example: | |
# | |
# h = { '1' => 'one', '2' => 'two', 3 => 'three'} | |
# h[:one, :three, :two] = h[ '1', '3', '2'] | |
# p h # => {"1"=>"one", "2"=>"two", 3=>"three", :one=>"one", :three=>nil, :two=>"two"} | |
# | |
class Hash | |
alias :set :[]= | |
# Assign several values to keys: | |
# hash[:id,:name] = [1, 'Sergey'] | |
def []= *args | |
args.length == 2 ? set(*args) : args[0...-1].zip(args[-1]).each { |k,v| set(k,v) } | |
end | |
alias :get :[] | |
# Get several values from hash with keys: | |
# my_id, my_name = hash[:id, :name] | |
def [] *args | |
args.length == 1 ? get(*args) : args.map {|a| get a } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment