Skip to content

Instantly share code, notes, and snippets.

@IanVaughan
Created June 6, 2013 08:40
Show Gist options
  • Save IanVaughan/5720166 to your computer and use it in GitHub Desktop.
Save IanVaughan/5720166 to your computer and use it in GitHub Desktop.
Very basic way to access ruby hashes via method name.
module HashAccessor
def method_missing(name, *args, &block)
h = Hash[self.map{|(k,v)| [k.to_sym,v]}]
if h.has_key?(name.to_sym)
h[name.to_sym]
end
end
end
describe HashAccessor do
class Hash
include HashAccessor
end
context "hash symbol keys" do
subject { {a: 1, b: 2} }
its(:a) { should == 1 }
its(:b) { should == 2 }
its(:c) { should be_nil }
its('a') { should == 1 }
its('b') { should == 2 }
its('c') { should be_nil }
end
context "hash string keys" do
subject { {'a' => 1, 'b' => 2} }
its(:a) { should == 1 }
its(:b) { should == 2 }
its(:c) { should be_nil }
its('a') { should == 1 }
its('b') { should == 2 }
its('c') { should be_nil }
end
context "empty hash" do
subject { {} }
its(:a) { should be_nil }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment