On Wednesday 20 August 2008, Nick Brown wrote:
> F. Senault wrote:
> > Please provide some code to demonstrate this.
>
> #!/usr/bin/env ruby
>
> require 'sqlite3'
> db = SQLite3::Database.new('test.sqlite')
> db.execute ('drop table if exists example') # clean up incase of
> multiple runs
> db.execute('create table example (aval)')
>
> require 'cgi'
> cgi = CGI.new('html4')
>
> a = cgi['a']
>
> a.sub!(/hi/, 'bye')
> # to see expected behavior, replace the above with: a = a.sub(/hi/,
> 'bye')
>
> puts "Inserting value a=#{a} into the database.\n"
> sql = "insert into example (aval) values (?)"
> db.execute(sql, a)
>
> sql = "select aval from example"
> val = db.get_first_value(sql)
> puts "What was actually inserted into the database: #{val}\n"
>
>
> ########---------- end of code
>
> To run this, type "a=hi"[enter][ctrl-d] to simulate the behavior of a
> cgi session. You will get the output:
>
> Inserting value a=bye into the database.
> What was actually inserted into the database: hi
>
> Since other responders seem to think I expect sub to behave the same as
> sub!, I don't. I expect str.sub! to modify str, and I expect str.sub to
> return a modified copy of the str. This is not the same behavior.

If in your first post you'd have stated more clearly what you expected and 
what you instead got, we wouldn't have misunderstood your needs. After all, 
the only (or, at least, main) difference between sub and sub! is the one I 
spoke of in my other answer. However, I can't try your code, as I don't have 
the sqlite gem/library. Would you please post what you get using sub and what 
you get using sub!?

The line 

puts "Inserting value a=#{a} into the database.\n"

displays the correct value (a=bye). If I understand you correctly, the 
surprising behavior comes from inserting it in the database. Posting what you 
get from the other puts will enable also those who don't have sqlite to help 
you.

(By the way, you don't need to put the \n at the end of the string with puts).

Stefano