Reputation: 10043
I'm writing a ruby script and looking to execute the native Sql queries.
I/p arr = ["1", 2, "3", 5, 6]
Expected o/p:
arr = (1,2,3,4)
It has to be something simple which i'm missing, join always gives me "(1,2,3,4)" which when used in query like
select * from users where id IN (1,2,3,4)
should work. Currently when "(1,2,3,4)" is used as input, only id is matched with is 1.
EDIT:
I'm using mysql.
require 'mysql2'
client = Mysql2::Client.new(:host => @db_host, :username => @db_user, :password => @db_pass, :database => @db_name, :port => @port)
Any quick solution will be of help
Upvotes: 0
Views: 39
Reputation: 19948
inp = ["1", 2, "3", 5, 6]
outp = "(#{inp.join(',')})"
# => "(1,2,3,5,6)"
Upvotes: 1
Reputation: 6572
Use Array#join.
here is my sample table
$ sqlite3 test.db
SQLite version 3.11.0 2016-02-15 17:29:24
Enter ".help" for usage hints.
sqlite> select * from cars;
1|Audi|52642
2|Mercedes|57127
3|Skoda|9000
4|Volvo|29000
5|Bentley|350000
6|Citroen|21000
7|Hummer|41400
8|Volkswagen|21600
below code shows how to query (this is almost same in mysql/postgres etc.) with in clause given an array.
$ irb
2.3.1 :001 > require 'sqlite3'
# => true
2.3.1 :002 > db = SQLite3::Database.open 'test.db'
# => #<SQLite3::Database:0x00000000d892d0 @tracefunc=nil, @authorizer=nil, ...
2.3.1 :003 > qry = "select * from Cars where id in (#{[1,2,3,4, "5"].join(", ")})"
# => "select * from Cars where id in (1, 2, 3, 4, 5)"
2.3.1 :004 > db.execute qry
# => [[1, "Audi", 52642], [2, "Mercedes", 57127], [3, "Skoda", 9000], [4, "Volvo", 29000], [5, "Bentley", 350000]]
Upvotes: 1