# Overriding indexers

**URL:** <https://www.ruby-forum.com/t/overriding-indexers/181000>\
**Category:** IronRuby\
**Created:** [January 3, 2010, 4:11pm UTC](https://www.ruby-forum.com/t/overriding-indexers/181000 "2010-01-03T16:11:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![barby](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/c57346/32.png) [@barby](https://www.ruby-forum.com/u/barby)\
**Post date:** [January 3, 2010, 4:11pm UTC](https://www.ruby-forum.com/t/overriding-indexers/181000/1 "2010-01-03T16:11:15Z")

</div>

Hi

A while ago there were the methods **getitem** and **setitem** which  
allowed  
to override an indexer.  
I can’t find these methods anymore and I also can’t find a way to  
override  
an indexer.

namespace ClrModels {

```
public class IndexerContained{

    private Dictionary<string, string> _inner = new 

```

Dictionary\<string,  
string\>{  
{ “key1”, “value1” },  
{ “key2”, “value2” },  
{ “key3”, “value3” },  
{ “key4”, “value4” }  
};

```
    public virtual string this[string name]{
      get { return _inner[name]; }
      set { _inner[name] = value; }
    }
}

public class IndexerCaller{

    public string CallIndexOnClass(IndexerContained klass, string 

```

name){  
return klass[name];  
}

```
    public string CallIndexOnInterface(IHaveAnIndexer klass, string

```

name){  
return klass[name];  
}

```
}

```

}

class MySubIndexer \< ClrModels::IndexerContained;  
def ; 6; end;  
def Item(name); 7; end;  
def item(name); 8; end;  
def get\_Item(name); 9; end;  
end

> > cons = ClrModels::IndexerCaller.new  
> > =\> ClrModels.IndexerCaller  
> > cons.call\_index\_on\_class(MySubIndexer.new, “key”)  
> > unknown:0: warning: do not use Fixnums as Symbols  
> > =\> ‘Fail’

And a spec to go with it:

require File.dirname( **FILE** ) + “/…/spec\_helper”

describe “CLR to CLR interactions” do

describe “when isolating CLR classes” do

```
describe "that have an indexer" do
  before do
    @cons = ClrModels::IndexerCaller.new
    @ind = Caricature::Isolation.for(ClrModels::IndexerContained)
  end

  it "should work without expectations" do
    @cons.call_index_on_class(@ind, "key1").should.be.nil
  end

  it "should work with an expectation" do
    @ind.when_receiving(: __getitem__ ).return("5")

    @cons.call_index_on_class(@ind, "key1").should.equal "5"
  end

end

```

end

## end

Met vriendelijke groeten - Best regards - Salutations  
Ivan Porto C.  
Blog: [http://flanders.co.nz](http://flanders.co.nz)  
Google Wave: removed\_email\_address@domain.invalid  
Twitter: [http://twitter.com/casualjim](http://twitter.com/casualjim)  
Author of IronRuby in Action ([http://manning.com/carrero](http://manning.com/carrero))
