From: "Florian Groß" Date: 2003-06-05T06:42:06+09:00 Subject: Re: case of sub! not working This is a multi-part message in MIME format. --------------040007020705010202080704 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Ian Macdonald wrote: > Hi, Moin! > irb(main):002:0> ENV['PATH'].sub!(%r(:/usr/kerberos/bin), '') > => "/usr/bin:/bin:/usr/X11R6/bin:/usr/pubsw/bin" > irb(main):003:0> ENV['PATH'] > => "/usr/bin:/bin:/usr/X11R6/bin:/usr/pubsw/bin:/usr/kerberos/bin" > > Why doesn't the sub! work in line 002? It returns the correct answer, > but ENV['PATH'] is not modified in-place. You now know why this isn't the case, but I chose to try making it work anyway. I attached a small hack which changes the original ENV[] and ENV[]= so that they return a proxy to the real contents which changes ENV[] when it is changed. This allows you to do this: ENV['foo'] = "hello world" # => "hello world" ENV['foo'].replace("whatever").reverse!.gsub!(/[aeiou]/, "*") # => "r*v*t*hw" ENV['foo'] # => "r*v*t*hw" I didn't really test this in detail so it might have small bugs or break your Ruby into tiny little shivers. Regards, flgr --------------040007020705010202080704 Content-Type: text/plain; name="proxied_env.rb" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="proxied_env.rb" class << ENV class EnvEntryProxy def initialize(entry_name) @entry_name = entry_name end def method_missing(method_name, *args) entry = ENV.old_get(@entry_name) result = entry.send(method_name, *args) ENV.old_set(@entry_name, entry) result = EnvEntryProxy.new(@entry_name) if result.id == entry.id return result end ["to_s","to_a","inspect","==","=~","==="].each { |method_name| class_eval <<-END def #{method_name}(*args) method_missing('#{method_name}', *args) end END } end alias :old_get :[] def [](entry_name) EnvEntryProxy.new(entry_name) end alias :old_set :[]= def []=(entry_name, new_value) old_set(entry_name, new_value) EnvEntryProxy.new(entry_name) end end --------------040007020705010202080704--