Case-insensitive hash?

  • Thread starter Gregory Seidman
  • Start date
G

Gregory Seidman

So I understand that a hash can use keys of any type, not just string (or
symbol), but there are occasions when I have a hash that has been populated
with string keys whose values I would like to access case-insensitively. Is
there a setting or something? Do I have to write a wrapper to deal with it?

--Greg
 
A

Austin Ziegler

So I understand that a hash can use keys of any type, not just string (or
symbol), but there are occasions when I have a hash that has been populat= ed
with string keys whose values I would like to access case-insensitively. = Is
there a setting or something? Do I have to write a wrapper to deal with i=
t?

You will need to write a wrapper. Look at HashWithIndifferentAccess in
Rails for an example of how to do this.

-austin
 
E

Eero Saynatkari

--Fba/0zbH8Xs+Fj9o
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

So I understand that a hash can use keys of any type, not just string (or
symbol), but there are occasions when I have a hash that has been populat= ed
with string keys whose values I would like to access case-insensitively. = Is
there a setting or something? Do I have to write a wrapper to deal with i=
t?

If you always access that particular Hash case-insensitively, then
the simplest solution would be to filter input to it:

@hash[key.downcase] =3D value

If, on the other hand, you alter between sensitive and insensitive,
you would filter the output instead=20

# (Naively)
nil unless @hash.keys.find {|k| key.downcase =3D=3D k.downcase}
@hash[key]

If you need to, you could encapsulate this behaviour in a subclass.


E

--Fba/0zbH8Xs+Fj9o
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (FreeBSD)

iD8DBQFDwDovxvA1l6h+MUMRAvltAKCKpRUh2PsCnWpEg5wkHwPF6LT/uwCffXRa
8UhjwHGp/RW33ccPC3POnDs=
=4qY2
-----END PGP SIGNATURE-----

--Fba/0zbH8Xs+Fj9o--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,173
Latest member
GeraldReund
Top