-
-
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.
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
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