LoginSignup
0
0

More than 5 years have passed since last update.

Ruby単体でRedisを触るサンプル

Posted at

Railsからredisを使うみたいな記事は結構見つけたんですが、もうちょっとシンプルに試してみたいなと調べてたら意外と情報少なかったので書いてみます。

環境

Windows10
ruby 2.4.4p296

準備

Redisをローカルにインストール
http://kageura.hatenadiary.jp/entry/2017/11/30/Windows%E7%89%88Redis%E3%82%92%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB%E3%81%97%E3%81%A6%E8%A7%A6%E3%81%A3%E3%81%A6%E3%81%BF%E3%82%8B

gem redis をインストール

$ gem install redis

適当なフォルダでこのコードを実行

redis_sample.rb

require 'redis'

@redis = Redis.new

def set_data(*args)
  args.each_with_index do |val, idx|
    @redis.set val, idx
  end
end

def output_data
  keys = @redis.keys

  rows = []
  keys.each do |key|
    ret = @redis.get(key.to_s)
    rows << [key.to_s, ret.to_s]
  end
  p rows
end

# 値をset
set_data('fuga')
set_data('red', 'green', 'blue')
output_data

# 値を削除
@redis.del 'red'
output_data

# 値を全て削除
@redis.flushall
output_data

結果

["red", "0"], ["fuga", "0"], ["blue", "2"], ["green", "1"]]
[["fuga", "0"], ["blue", "2"], ["green", "1"]]
[]

参考記事

https://inokara.hateblo.jp/entry/2013/06/30/144815
http://redis.shibu.jp/commandreference/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0