Forum: Ruby Case-insensitive hash?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bf6862e2a409078e13a3979c00bba1d6?d=identicon&s=25 Gregory Seidman (Guest)
on 2006-01-06 21:07
(Received via mailing list)
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
31ab75f7ddda241830659630746cdd3a?d=identicon&s=25 Austin Ziegler (Guest)
on 2006-01-06 21:31
(Received via mailing list)
On 06/01/06, Gregory Seidman <gsslist+ruby@anthropohedron.net> wrote:
> 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?

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

-austin
5c7bdd14d6885c8275eaf78be41d120a?d=identicon&s=25 Eero Saynatkari (Guest)
on 2006-01-06 23:04
(Received via mailing list)
On 2006.01.07 05:05, Gregory Seidman wrote:
> 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?

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

  @hash[key.downcase] = value

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

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

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

> --Greg


E
This topic is locked and can not be replied to.