Forum: Ruby Hash key formatter

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.
45196398e9685000d195ec626d477f0e?d=identicon&s=25 unknown (Guest)
on 2006-05-11 19:09
(Received via mailing list)
Add an attribute to Hash to store transformation of keys. For instance:

  h = Hash.new
  h.key_format do |k|
    k.to_s.downcase.to_sym
  }

  h['BIG'] = 10
  h  #=>  { :big => 10 }

Good little RCR.
E1d641bfe4071a5413bac781f06d3fd1?d=identicon&s=25 Sean O'halpin (sean)
on 2006-05-12 01:18
(Received via mailing list)
On 5/11/06, transfire@gmail.com <transfire@gmail.com> wrote:
> Add an attribute to Hash to store transformation of keys.

I like the idea. Here's a simple-minded implementation:

class Hash
  def key_format(&block)
    @key_format ||= proc {|x| x}
    @key_format = block_given? ? block : @key_format
  end

  # look ma! no aliases (but less efficient)
  prev_store = instance_method(:store)
  define_method :store do |key, value|
    prev_store.bind(self).call(key_format.call(key), value)
  end

  def []=(key, value)
    store(key, value)
  end
end

h = Hash.new

h[:a] = 1
p h

h['A'] = 1,2,3
p h
p h.key_format

f = Hash.new
f.key_format {|key| key.to_s.downcase.to_sym }

f[:a] = 1
p f

f['A'] = 1,2,3
p f

p f.key_format

---------- Ruby ----------
{:a=>1}
{"A"=>[1, 2, 3], :a=>1}
#<Proc:0x02886ca0@C:/rubylib/experiments/hash-format-key.rb:3>
{:a=>1}
{:a=>[1, 2, 3]}
#<Proc:0x02885c38@C:/rubylib/experiments/hash-format-key.rb:29>

Output completed (0 sec consumed) - Normal Termination

I'm just playing with the idea of avoiding aliases - I'd probably use
a GUID alias in production to avoid the overhead of rebinding the old
:store method on every store.

Regards,
Sean
E0ed615bd6632dd23165e045e3c1df09?d=identicon&s=25 Florian GroÃ? (Guest)
on 2006-05-13 16:18
(Received via mailing list)
transfire@gmail.com wrote:

> Good little RCR.
Hm, Hash::MixIn already supports this for hash-like classes. See
attachment.
This topic is locked and can not be replied to.