Method: Redis::Commands::SortedSets#zrandmember

Defined in:
lib/redis/commands/sorted_sets.rb

#zrandmember(key, count = nil, withscores: false, with_scores: withscores) ⇒ nil, ...

Get one or more random members from a sorted set.

Examples:

Get one random member

redis.zrandmember("zset")
  # => "a"

Get multiple random members

redis.zrandmember("zset", 2)
  # => ["a", "b"]

Get multiple random members with scores

redis.zrandmember("zset", 2, with_scores: true)
  # => [["a", 2.0], ["b", 3.0]]

Parameters:

  • key (String)
  • count (Integer) (defaults to: nil)
  • options (Hash)
    • ‘:with_scores => true`: include scores in output

Returns:

  • (nil, String, Array<String>, Array<[String, Float]>)
    • when ‘key` does not exist or set is empty, `nil`

    • when ‘count` is not specified, a member

    • when ‘count` is specified and `:with_scores` is not specified, an array of members

    • when ‘:with_scores` is specified, an array with `[member, score]` pairs



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/redis/commands/sorted_sets.rb', line 262

def zrandmember(key, count = nil, withscores: false, with_scores: withscores)
  if with_scores && count.nil?
    raise ArgumentError, "count argument must be specified"
  end

  args = [:zrandmember, key]
  args << Integer(count) if count

  if with_scores
    args << "WITHSCORES"
    block = FloatifyPairs
  end

  send_command(args, &block)
end