Overriding ENV[]

J

Jos Backus

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

Jesús Gabriel y Galán

$ cat x
#!/usr/bin/env ruby
class << ENV
=A0define_method:)[], lambda { |v| v.upcase })
end
p ENV['FOO']
$ FOO=3Dfoo ./x
=A0"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 =3D [1,2,3]
=3D> [1, 2, 3]
irb(main):005:0> class << a
irb(main):006:1> alias_method :eek:ld, :[]
irb(main):007:1> end
=3D> #<Class:#<Array:0x2932038>>
irb(main):008:0> a.old(0)
=3D> 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
=3D> nil
irb(main):014:0> a[0]
=3D> "1"

I tested with an array, but ENV should work too.
 
J

Jos Backus

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 :eek:ld, :[]
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 :eek:ld_[], :[]

which produces a syntax error. I should have tried a little harder.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top