Note that there are some explanatory texts on larger screens.

plurals
  1. PORedefining String's gsub
    primarykey
    data
    text
    <p>I am new to ruby and I just come across my first tricky problem. I am trying to redefine some methods of String in order to attach some functionality around them. The problematic method appears to be gsub. (EDIT) Let me paste my main.rb that showcases this error.</p> <pre><code>require 'rubygems' if RUBY_VERSION &lt; "1.9" require 'sinatra' class String alias_method :old_gsub, :gsub def gsub (*params, &amp;block ) old_gsub *params, &amp;block end end get '/' do s="Hello world! " end </code></pre> <p>This is my starting point and I expect this to work just as the original String does. Unfotunately, with this redefinition in place, some existing code breaks.</p> <p>As you can see in this script, I try to load Sinatra and serve a page. When I do this and request the index, the web server fails with the following output in the console.</p> <blockquote> 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 method `upcase' 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 </blockquote> <blockquote> [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 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 </blockquote> <p>The first exception (httpresponse.rb:172) is on the line</p> <pre><code>tmp = key.gsub(/\bwww|^te$|\b\w/){ $&amp;.upcase } </code></pre> <p>and the second error is caused by the result of (accesslog.rb:50)</p> <pre><code>format_string.gsub(/\%(?:\{(.*?)\})?&gt;?([a-zA-Z%])/) </code></pre> <p>From the above, it appers that I am using Ruby 1.9.1 (even though ruby -v gives me 1.9.2p0). I'm on Ubuntu 10.04. It is true that there may be something wrong in my configuration of Ruby, installing it in Ubuntu was a bit messy.</p> <p>So, to sum up, why does my redefinition of gsub behave differenlty than the original gsub?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload