Skip to content

Instantly share code, notes, and snippets.

View double_dispatch.rb
#!/usr/bin/ruby
OPS = {}
def OPS.[](cmd, *arg)
self.fetch([cmd, arg.first.class])[*arg]
end
Constant = Struct.new(:value) do
def initialize(v)
View dns-tester.rb
require 'socket'
ARGF.each do |line|
if /^\s*(\S+)\s+((?:\d{1,3}\.){3}\d{1,3})(?!\d)/ =~ line
host = $1
listed_ip = $2
begin
addrinfo = Socket::getaddrinfo(host, nil, :INET)
returned_ips = addrinfo.map {|a| a[3]}
@rklemme
rklemme / measure-struct-vs-hash.rb
Last active Aug 29, 2015
Benchmark of creating 1,000,000 objects of a Struct generated class, OpenStruct and Hash
View measure-struct-vs-hash.rb
#!/usr/bin/ruby
require 'benchmark'
require 'ostruct'
REP = 10**6
Cl = Struct.new :name, :age
Benchmark.bmbm 20 do |x|
View encoding-line-break-test.rb
#!/usr/bin/ruby -w
FILE_NAME = "x"
printf "%-20s %p\n%-20s %p\n",
"Default external", Encoding.default_external,
"Default internal", Encoding.default_internal
# p File.instance_methods.grep(/enc|opt/)
@rklemme
rklemme / MichaelsLock.rb
Last active Aug 29, 2015
Data structure where only one thread is allowed to write
View MichaelsLock.rb
class MichaelsLock
def initialize
@mx = Mutex.new
end
def lock_writer
@mx.synchronize do
raise "Already locked" if @writer
@writer = Thread.current
@rklemme
rklemme / make_xpath.rb
Created Jan 8, 2015
Create XPath from XML node structure
View make_xpath.rb
def make_xpath(node, xpath = "//")
xpath << node.name
first = true
node.attributes.values.each do |attr|
if first
first = false
xpath << "["
else
@rklemme
rklemme / proc-return.rb
Created Jan 6, 2015
Test different handling of return in lambda, proc and Proc.new
View proc-return.rb
class X
def initialize
@l = lambda { return 123 }
@p = proc { return 456 }
@o = Proc.new { return 789 }
end
def l; @l.call end
def p; @p.call end
@rklemme
rklemme / marshal-logger.rb
Created Dec 1, 2014
How to marshal an object with open stream, file descriptor or other non serializable data
View marshal-logger.rb
#!/usr/bin/ruby
class Logger
ENDL = "\n".freeze
def initialize(file_name)
@file_name = file_name
end
def log(message)
@rklemme
rklemme / get-groups.rb
Created Oct 24, 2014
Script extracting group information from a text file
View get-groups.rb
#!/usr/bin/ruby -w
Group = Struct.new :name, :primary, :secondary, :editors
GET_UID = /uid=([^,]*)/
EXTRACT = {
"dn" => [:name, /cn=([^,]*)/],
"owner" => [:primary, GET_UID],
"seeAlso" => [:secondary, GET_UID],
@rklemme
rklemme / TestBufferingForCharIO.java
Last active Aug 29, 2015
Test program to investigate effects of buffering and buffer sizes for char based input from file.
View TestBufferingForCharIO.java
package file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;