Overriding ENV[]

$ 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?

On Mon, Aug 9, 2010 at 11:01 PM, Jos B. [email protected] wrote:

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
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.

On Tue, Aug 10, 2010 at 06:58:00AM +0900, Jess Gabriel y Galn wrote:

irb(main):009:0> class << a
irb(main):010:1> def
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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs