Created
March 14, 2012 10:02
-
-
Save codesnik/2035501 to your computer and use it in GitHub Desktop.
Hash lvalue slice monkey patch
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
# lvalue slicing of Hashes | |
# hash = {foo: 1, bar: 2, baz: 3} | |
# hash[:foo, :bar] == [1, 2] | |
# | |
# hash[:foo, 3] = 6,7 | |
# hash == {foo: 6, bar: 2, baz: 3, 3 => 7} | |
# | |
# strange enough, I haven't noticed any slowdown on rails startup. | |
class Hash | |
alias oldbracket [] | |
def [](*values) | |
if values.size == 1 | |
oldbracket(*values) | |
else | |
values_at(*values) | |
end | |
end | |
alias oldbracketassign []= | |
def []=(*args) | |
if args.size == 2 | |
oldbracketassign(*args) | |
else | |
vals = args.pop | |
args.zip(vals) do |key, val| | |
oldbracketassign key, val | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment