所以我需要在Ruby中运行一个循环来将一些字符串传递给SQLite。基本上我有一个看起来像这样的表:
pID Data
1649,1650,1651|Some data
1643,3|some more data
23,4,5,6,7|More data
现在在我的SQLite查询中,我有时需要将给定行的所有pID作为一个整个字符串传递,我可以轻松地在下面的循环中使用'i'变量:
pID = db.execute( "select distinct pID from pmesh")
pID.each do |i|
end
其中'i'将等于每个pID行,每个字符串如下所示:
1649,1650,1651
1643,3
23,4,5,6,7
但有时候我需要每个字符串看起来像这样让我通过它们:
"1649","1650","1651"
"1643","3"
"23,"4","5","6","7"
是否有任何简单的循环可以使用引号和正确的逗号来使字符串显示为我想要的?我知道我可以做“i = i.to_s()和a = i.split(”,“)”,但在那之后我真的不知道其他的循环方式。
谢谢, 波比
答案 0 :(得分:2)
我认为你正在寻找这个:
i.split(",").map { |x| '"' + x + '"' }.join(",")
或者这个:
i.gsub(/[0-9]+/, '"\0"')
答案 1 :(得分:0)
以下是一个例子:
x = [1,2,4,5,6]
=> [1,2,4,5,6]
x.collect { |i| "#{i}" }
= > ["1","2","4","5","6"]
或者,如果你想将它们加入一个字符串:
x.collect { |i| "#{i}" }.join(', ')
或者,如果您的输入是csv字符串:
x.split(",").collect { |i| "#{i}" }.join(', ')
编辑:
以下是我认为你想要做的一个例子。
require 'sqlite3'
db = SQLite3::Database.new("test.db")
db.execute("create table bobby (pID varchar2(50), Data varchar(100))")
db.execute("select * from bobby")
db.execute("insert into bobby values ( ? , ?)", "1649,1650,1651", "Some Data1")
db.execute("insert into bobby values ( ? , ?)", "1643,3", "Some Data2")
db.execute("insert into bobby values ( ? , ?)", "23,4,5,6,7", "Some Data3")
db.execute("select * from bobby").each do |row|
p
end
# outputs [["1649,1650,1651", "Some Data1"], ["1643,3", "Some Data2"], ["23,4,5,6,7", "Some Data3"]]
db.results_as_hash = true #allows hashing row via column name
puts "Each ID as array of strings"
db.execute("select * from bobby").each do |row|
p row['pID'].split(",").collect { |i| "#{i}" }
end
puts "Each ID as single string"
db.execute("select * from bobby").each do |row|
p row['pID'].split(",").collect { |i| "#{i}" }.join(", ")
end
这是输出:
C:\Users\Jim\Desktop>ruby sqlLiteExample.rb
Each ID as array of strings
["1649", "1650", "1651"]
["1643", "3"]
["23", "4", "5", "6", "7"]
Each ID as single string
"1649, 1650, 1651"
"1643, 3"
"23, 4, 5, 6, 7"
EDIT2: 如果你希望你的值是一个字符串,例如“”1643“,”3“”,那么你将不得不做以下事情:
x.map{|i| '"' + "#{i}" + '"' }.join(',')
# outputs "\"124\",\"5525\",\"23525\""