Text processing with Ruby regular expressions and blocks
This example will find all code tags and pass the lang attribute’s value and the code block’s content to the block:
1 output = r.gsub(/<code[\.|\:]([\w\-]+)>(.*?)<\/code[\.|\:]?\1?>/m) do 2 lang, text = $1, $2 3 html = "<notextile>" + text + "</notextile>" 4 end.to_html
The block’s return value will replace the found tag.
Ruby Hash except and only
1 class Hash 2 def except(*blacklist) 3 reject {|key, value| blacklist.include?(key) } 4 end 5 6 def only(*whitelist) 7 reject {|key, value| !whitelist.include?(key) } 8 end 9 end
Stringify a Ruby Hash
1 class Hash 2 def stringify 3 inject({}) do |options, (key, value)| 4 options[key.to_s] = value.to_s 5 options 6 end 7 end 8 9 def stringify! 10 each do |key, value| 11 delete(key) 12 store(key.to_s, value.to_s) 13 end 14 end 15 end
How to install Tokyo Tyrant, Tokyo Cabinet and rufus-tokyo
1 git clone git://github.com/etrepum/tokyo-cabinet.git 2 git clone git://github.com/etrepum/tokyo-tyrant.git 3 4 5 cd tokyo-cabinet/ 6 ./configure 7 make 8 sudo make install 9 10 cd .. 11 12 cd tokyo-tyrant/ 13 ./configure 14 make 15 sudo make install 16 17 ttserver -port 45001 data.tch 18 19 sudo gem install rufus-tokyo 20 21 cat <<EOF >>test.rb 22 23 require 'rubygems' 24 require 'rufus/tokyo/tyrant' 25 require 'benchmark' 26 27 28 #db = Rufus::Tokyo::Cabinet.new('data.tch') 29 30 db = Rufus::Tokyo::Tyrant.new('localhost', 45001) 31 32 seconds = Benchmark.realtime do 33 for i in 1..1000000 34 db['nada' + i.to_s] = 'surf' + i.to_s 35 end 36 end 37 38 puts seconds 39 db.close 40 41 EOF 42 43 ruby test.rb
Gotchas
One gotcha I learned was that you should only use strings not symbols. If you use symbols you’ll get this weird error:
1 Invalid String value
Another gotcha is that Tokyo Cabinet will lock a database. If you try to open the same database from another process it will wait for the other process to close the database.
Debian
On Debian you need to install bzlib before installing tokyo-cabinet:
1 apt-get install libbz2-dev
How to install and use Redis with Ruby
1 git clone git://github.com/ezmobius/redis-rb.git 2 cd redis-rb/ 3 rake redis:install 4 rake dtach:install 5 rake redis:start & 6 rake install 7 8 cat <<EOF >>test.rb 9 require 'rubygems' 10 require 'redis' 11 12 r = Redis.new 13 14 r.delete('foo') 15 16 p'set foo to "bar"' 17 r['foo'] = 'bar' 18 19 p 'value of foo' 20 p r['foo'] 21 EOF 22 23 ruby test.rb
If Redis is not started Ruby will exit at Redis.new for some reason without saying anything.