I am new to ruby ββand I just run into the first difficult problem. I am trying to override some String methods in order to attach some functionality to them. The problematic method seems to be gsub. (EDIT) Let me insert my main.rb, which demonstrates this error.
require 'rubygems' if RUBY_VERSION < "1.9" require 'sinatra' class String alias_method :old_gsub, :gsub def gsub (*params, &block ) old_gsub *params, &block end end get '/' do s="Hello world! " end
This is my starting point, and I expect this to work the same as the original line. Unfortunately, with this redefinition in place, there are some existing code breaks.
As you can see in this script, I am trying to load Sinatra and serve the page. When I do this and request the index, the web server fails with the next console output.
127.0.0.1 - - [25 / Feb / 2011 17:56:26] "GET / HTTP / 1.1" 200 13 0.0012 [2011-02-25 17:56:26] ERROR NoMethodError: undefined `upcase 'method for nil: NilClass / usr / local / ruby ββ/ lib / ruby ββ/ 1.9.1 / webrick / httpresponse.rb: 172: in `block (2 levels) in send_header '/data/Dropbox/Ruby/RubyTrack/lib/main.rb:227 : in `gsub '/data/Dropbox/Ruby/RubyTrack/lib/main.rb:227:in` gsub' / usr / local / ruby ββ/ lib / ruby ββ/ 1.9.1 / webrick / httpresponse.rb: 172: in `block in send_header '+ plus more stuff in the trace
[2011-02-25 17:56:26] ERROR NoMethodError: undefined `[] 'method for nil: NilClass / usr / local / ruby ββ/ lib / ruby ββ/ 1.9.1 / webrick / accesslog.rb: 52: in block in the format '/data/Dropbox/Ruby/RubyTrack/lib/main.rb:227:in `gsub' /data/Dropbox/Ruby/RubyTrack/lib/main.rb:227:in` gsub '/ usr / local / ruby / lib / ruby ββ/ 1.9.1 / webrick / accesslog.rb: 50: in `format '+ more stuff in the trace
The first exception (httpresponse.rb: 172) is on the line
tmp = key.gsub(/\bwww|^te$|\b\w/){ $&.upcase }
and the second error is caused by the result (accesslog.rb: 50)
format_string.gsub(/\%(?:\{(.*?)\})?>?([a-zA-Z%])/)
From the above it can be seen that I'm using Ruby 1.9.1 (although ruby ββ-v gives me 1.9.2p0). I'm on Ubuntu 10.04. Itβs true that there might be something wrong with my Ruby configuration, the installation on Ubuntu was a bit dirty.
So, to summarize, why does my gsub override behave differently than the original gsub?
source share