randombits
randombits

Reputation: 48450

Redis-rb pushing an array via redis.lpush is flattening the list

I am attempting to push multiple values to a redis LIST using LPUSH. The code looks something like this:

mylist = ["1", "2", "3", "4"]
$redis.lpush(name, mylist)

The problem with the above is the list gets flattened to look like "1234". How do I use LPUSH in this case to push 4 individual elements to the name array?

Upvotes: 6

Views: 5583

Answers (3)

Gabriel
Gabriel

Reputation: 169

With v 3.0 + the syntax is

r= Redis.new()

r.lpush("mylist", ["element1", "element2" , "element3"])

Upvotes: 0

Didier Spezia
Didier Spezia

Reputation: 73226

You may want to have a look at:

Redis-rb version 2.2.2 does not support variadic commands. They have been introduced for version 3.0, but it has not been delivered yet.

There is no specific method to deal with arrays in variadic parameters commands. Your code will probably work fine with version 3.0.

In the meantime, I suggest you use a pipeline such as:

name = "toto"
mylist = [ 1,2,3,4,5 ]
$redis.pipelined{ mylist.each{ |x| $redis.lpush(name,x) } }

With the pipeline, the number of roundtrips will be the same than using variadic parameters commands.

If you really want to use variadic parameters commands, you can easily install a prerelease version of 3.0 using:

gem install --prerelease redis
gem list redis 

*** LOCAL GEMS ***
redis (3.0.0.rc1, 2.2.2)

and activate it in your script by using:

gem 'redis', '3.0.0.rc1'
require 'redis'

Please note that if you have other gems depending on the redis gem, you will have some dependency issues. Better to wait for the official delivery IMO.

Upvotes: 3

Phrogz
Phrogz

Reputation: 303224

You could do:

# If you want ["1","2","3","4",...restofarray...]
mylist.reverse.each{ |v| $redis.lpush(name,v) }

# If you want ["4","3","2","1",...restofarray...]
mylist.each{ |v| $redis.lpush(name,v) }

Upvotes: 0

Related Questions