Gih's Blog

只言片语

如何优化这段代码

2013-04-15 by gihnius, tagged as ruby

code:

def insert(hash)
  cols = ""
  vals = ""
  hash.each do |c,v|
    unless v.nil?
      cols << "#{c},"
      if v.is_a?(String)
        vals << "'#{PGconn.escape(v)}',"
      else
        vals << "#{v},"
      end
    end
  end
  vals.gsub!(/,$/, '')
  cols.gsub!(/,$/, '')
  sql = "INSERT INTO twitter_users(#{cols}) VALUES(#{vals});"
  #puts_and_return sql
  begin
    db.async_exec sql
  rescue PG::Error => e
    puts "Oops... >>> in #{hash} : #{e}"
  end
end

table 已确保可以容纳 hash

这种情况在ruby2 我会用 Struct.

这个方法有什么不妥之处,或者有没有更好的方法?