On Wed, Aug 20, 2008 at 5:01 PM, Nick Brown
<ruby-forum.com / nick-brown.com> wrote:
> "puts #{a}" outputs the modified version of a, but inserting that *exact
> same* string object into a database puts an UNMODIFIED version of the
> string into the DB. It's as if db.execute looks back in time to before
> the sub! when it gets the value of a. Something unexplained is going on
> here (unless the database module includes a time machine).

#!/usr/bin/env ruby

require 'rubygems'
require 'sqlite3'

module SQLite3
  class Statement
    def bind_params( *bind_vars )
      index = 1
p self.class, "bind_params()"
p bind_vars
p *bind_vars
      bind_vars.flatten.each do |var|
p var
        if Hash === var
          var.each { |key, val| bind_param key, val }
        else
          bind_param index, var
          index += 1
        end
      end
    end
  end
end

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"


(offline mode: enter name=value pairs on standard input)
a=hi
Inserting value a=bye into the database.
SQLite3::Statement
"bind_params()"
["bye"]
"bye"
"hi"
What was actually inserted into the database: hi