Skip to content

Instantly share code, notes, and snippets.

@burningTyger
Created January 3, 2013 16:41
Show Gist options
  • Save burningTyger/4444787 to your computer and use it in GitHub Desktop.
Save burningTyger/4444787 to your computer and use it in GitHub Desktop.
Here you have multi-key lookup for Ruby. Original idea by @txustice: https://twitter.com/txustice/status/286790996438683648 I can actually think of use cases :-) If you know a better way for dealing with that return value let me know.
class Hash
alias_method :original, :[]
def [](*keys)
keys.uniq!
if keys[1]
keys.map { |key| original key }
else
original keys[0]
end
end
end
require 'minitest/autorun'
describe Hash do
before do
@h = {:a => 1, :b => 2}
end
describe "[] multikey support" do
it 'must return single objects' do
@h[:a].must_equal 1
@h[:a, :a].must_equal 1
end
it 'must return an Array' do
@h[:a,:b].must_equal [1,2]
@h[:a,:b,:a,:b].must_equal [1,2]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment