Prev: Accessing programs through the terminal with ruby
Next: SSL Client Certificate error on Mac OS X 10.6.4
From: Jos Backus on 9 Aug 2010 17:01 $ cat x #!/usr/bin/env ruby class << ENV define_method(:[], lambda { |v| v.upcase }) end p ENV['FOO'] $ FOO=foo ./x "FOO" $ But what if I want to call the original ENV[] inside the new method? -- Jos Backus jos at catnook.com
From: Jesús Gabriel y Galán on 9 Aug 2010 17:58 On Mon, Aug 9, 2010 at 11:01 PM, Jos Backus <jos(a)catnook.com> wrote: > $ cat x > #!/usr/bin/env ruby > class << ENV > define_method(:[], lambda { |v| v.upcase }) > end > p ENV['FOO'] > $ FOO=foo ./x > "FOO" > $ > > But what if I want to call the original ENV[] inside the new method? You can use alias_method like this: irb(main):001:0> a = [1,2,3] => [1, 2, 3] irb(main):005:0> class << a irb(main):006:1> alias_method :old, :[] irb(main):007:1> end => #<Class:#<Array:0x2932038>> irb(main):008:0> a.old(0) => 1 irb(main):009:0> class << a irb(main):010:1> def [](val) irb(main):011:2> old(val).to_s.upcase irb(main):012:2> end irb(main):013:1> end => nil irb(main):014:0> a[0] => "1" I tested with an array, but ENV should work too.
From: Jos Backus on 9 Aug 2010 20:29
On Tue, Aug 10, 2010 at 06:58:00AM +0900, Jess Gabriel y Galn wrote: > You can use alias_method like this: > > irb(main):001:0> a = [1,2,3] > => [1, 2, 3] > irb(main):005:0> class << a > irb(main):006:1> alias_method :old, :[] > irb(main):007:1> end > => #<Class:#<Array:0x2932038>> > irb(main):008:0> a.old(0) > => 1 > irb(main):009:0> class << a > irb(main):010:1> def [](val) > irb(main):011:2> old(val).to_s.upcase > irb(main):012:2> end > irb(main):013:1> end > => nil > irb(main):014:0> a[0] > => "1" > > I tested with an array, but ENV should work too. This works, thanks Jes�s. I tried alias_method :old_[], :[] which produces a syntax error. I should have tried a little harder. -- Jos Backus jos at catnook.com |