Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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/

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away