Method: Redis::Commands::Hashes#hrandfield

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

#hrandfield(key, count = nil, withvalues: false, with_values: withvalues) ⇒ nil, ...

Get one or more random fields from a hash.

Examples:

Get one random field

redis.hrandfield("hash")
  # => "f1"

Get multiple random fields

redis.hrandfield("hash", 2)
  # => ["f1, "f2"]

Get multiple random fields with values

redis.hrandfield("hash", 2, with_values: true)
  # => [["f1", "s1"], ["f2", "s2"]]

Parameters:

  • key (String)
  • count (Integer) (defaults to: nil)
  • options (Hash)
    • :with_values => true: include values in output

Returns:

  • (nil, String, Array<String>, Array<[String, Float]>)
    • when key does not exist, nil
    • when count is not specified, a field name
    • when count is specified and :with_values is not specified, an array of field names
    • when :with_values is specified, an array with [field, value] pairs


138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/redis/commands/hashes.rb', line 138

def hrandfield(key, count = nil, withvalues: false, with_values: withvalues)
  if with_values && count.nil?
    raise ArgumentError, "count argument must be specified"
  end

  args = [:hrandfield, key]
  args << count if count
  args << "WITHVALUES" if with_values

  parser = Pairify if with_values
  send_command(args, &parser)
end