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.
Gregory S. (Guest)
on 2006-01-06 22: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
Austin Z. (Guest)
on 2006-01-06 22:31
(Received via mailing list)
On 06/01/06, Gregory S. <removed_email_address@domain.invalid> 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
Eero S. (Guest)
on 2006-01-07 00:04
(Received via mailing list)
On 2006.01.07 05:05, Gregory S. 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.