$ 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
$ 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
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.
On Mon, Aug 9, 2010 at 11:01 PM, Jos Backus <jos@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?
This works, thanks Jesús. I tried
alias_method :old_, :
which produces a syntax error. I should have tried a little harder.
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.
--
Jos Backus
jos at catnook.com