From: "David A. Black" Date: 2008-04-23T08:58:54+09:00 Subject: Re: Extending Hast class with custom [] []= methods --1926193751-1330942912-1208908734=:21639 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1330942912-1208908734=:21639" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1330942912-1208908734=:21639 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Wed, 23 Apr 2008, I=C3=B1aki Baz Castillo wrote: > Hi, I'd like to extend Hash class [] and []=3D methods in order to find a= key > with case insensitive. This is: > > > - The actual Hash [] behaviour: > > {"a"=3D>1,"b"=3D>2}["a"] > =3D> 1 > {"a"=3D>1,"b"=3D>2}["A"] > =3D> nil > > - The beaviour I look for: > > {"a"=3D>1,"b"=3D>2}["a"] > =3D> 1 > {"a"=3D>1,"b"=3D>2}["A"] > =3D> 1 > > > But I can't modify [] method since it's Ruby core written in C: > > ---------------------- > VALUE > rb_hash_aref(hash, key) > VALUE hash, key; > { > VALUE val; > > if (!st_lookup(RHASH(hash)->tbl, key, &val)) { > return rb_funcall(hash, id_default, 1, key); > } > return val; > } > ----------------------- > > > How could I do it? You can reopen the Hash class in Ruby, but it's not a good idea to change the documented behavior of core methods. A better way is to write a module, and then use it selectively for the hashes that need it: module CaseInsensitiveLookup def [](key) etc., and then: my_hash.extend(CaseInsensitiveLookup) David --=20 Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates! --1926193751-1330942912-1208908734=:21639-- --1926193751-1330942912-1208908734=:21639--