Skip to content

Instantly share code, notes, and snippets.

@sergeych
Created June 21, 2010 08:29
Show Gist options
  • Save sergeych/446581 to your computer and use it in GitHub Desktop.
Save sergeych/446581 to your computer and use it in GitHub Desktop.
Python-inspired Hash extension: index sequence getters/setters
# Python-inspired Hash extension: index sequence getters/setters
# author:: real.sergeych@gmail.com
#
# 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