8

I'm looking for some examples of getting and setting arrays of strings, and I can't seem to find one or make it work.

The strings themselves are SecureRandom.hex values. Think of them like invite codes. I want to create a pair of key/values:

1) Key=> invite:code:88bb4bdfef Value=> userid

2) Key=> userid:invite:codes Value => 88bb4bdfef,73dbfac453,etc... (one entry for each of the prior set)

I'm just getting stuck on managing the values in the second key/value pair.

UPDATE: So the challenge is that if I create an array and set it like so:

foo=Array.new
foo.push("abc")
foo.push("def")

at this point foo looks like: ["abc","def"]

So I set foo in redis, the retrieve it to bar:

$redis.set(:foo,foo)
bar=$redis.get(:foo)

Now bar looks like: "[\"abc\",\"def\"]"

Webjedi
  • 4,677
  • 7
  • 42
  • 59
  • Try to do it manually first with a couple of redis-cli commands ... it does not look so hard. – Didier Spezia May 30 '13 at 19:54
  • I did, see update. I can't (through ignorance most likely) convert that resultant string back to and array of strings. – Webjedi May 30 '13 at 22:46
  • you can JSON encode the array before storing, if you do not want to use lists as @Chris Heald suggested – akonsu May 31 '13 at 03:37

1 Answers1

16

You want lists or sets here, rather than simple keys. Here's an example using Redis' set functionality:

$redis.sadd("userid:invite:codes", ["88bb4bdfef", "73dbfac453"])
$redis.smembers("userid:invite:codes")
=> ["88bb4bdfef", "73dbfac453"]
Chris Heald
  • 61,439
  • 10
  • 123
  • 137
  • Related question...is the fact that I need to set two sets of keys to manage this process a sign I should not be using redis to do this? – Webjedi May 31 '13 at 18:03
  • 1
    Not necessarily. Redis is great, but it does take a bit of work to do some traditional DB stuff with. It's really up to your use case. – Chris Heald May 31 '13 at 19:58
  • To add to what Chris aptly stated, if you were doing this in an SQL DB such as PostgreSQL, you would create possibly two tables and then certainly create indices on them to handle the foreign keys. The second key, the set of IDs, is performing the same function as an index on a table would be. So you're not really doing extra work for it. You're making an extra call, but an RDBMS would add the same step. You're just more aware of it. – The Real Bill Jun 01 '13 at 16:04