Is the ruby operator ||= intelligent?

This is extremely easy to test: class MyCache def initialize @hash = {} end def []=(key, value) puts “Cache key ‘#{key}’ written” @hash[key] = value end def [](key) puts “Cache key ‘#{key}’ read” @hash[key] end end Now simply try the ||= syntax: cache = MyCache.new cache[“my key”] ||= “my value” # cache value was nil … Read more

Printing the source code of a Ruby block

You can do this with Ruby2Ruby which implements a to_ruby method. require ‘rubygems’ require ‘parse_tree’ require ‘parse_tree_extensions’ require ‘ruby2ruby’ def meth &block puts block.to_ruby end meth { some code } will output: “proc { some(code) }” I would also check out this awesome talk by Chris Wanstrath of Github http://goruco2008.confreaks.com/03_wanstrath.html He shows some interesting ruby2ruby … Read more

Ruby Hash with duplicate keys?

Two ways of achieving duplicate keys in a hash: h1 = {} h1.compare_by_identity h1[“a”] = 1 h1[“a”] = 2 p h1 # => {“a”=>1, “a”=>2} h2 = {} a1 = [1,2,3] a2 = [1,2] h2[a1] = 1 h2[a2] = 2 a2 << 3 p h2 # => {[1, 2, 3]=>1, [1, 2, 3]=>2}

Backslashes in single quoted strings vs. double quoted strings

Double-quoted strings support the full range of escape sequences, as shown below: \a Bell/alert (0x07) \b Backspace (0x08) \e Escape (0x1b) \f Formford (0x0c) \n Newline (0x0a) \r Return (0x0d) \s Space (0x20) \t Tab (0x09) \v Vertical tab (0x0b) For single-quoted strings, two consecutive backslashes are replaced by a single backslash, and a backslash … Read more

Spawn a background process in Ruby

As long as you are working on a POSIX OS you can use fork and exec. fork = Create a subprocess exec = Replace current process with another process You then need to inform that your main-process is not interested in the created subprocesses via Process.detach. job1 = fork do exec “/path/to/daemon01” end Process.detach(job1) …