Skip to content

Instantly share code, notes, and snippets.

#!/usr/bin/ruby
OPS = {}
def OPS.[](cmd, *arg)
self.fetch([cmd, arg.first.class])[*arg]
end
Constant = Struct.new(:value) do
def initialize(v)
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 August 29, 2015 14:16
Benchmark of creating 1,000,000 objects of a Struct generated class, OpenStruct and Hash
#!/usr/bin/ruby
require 'benchmark'
require 'ostruct'
REP = 10**6
Cl = Struct.new :name, :age
Benchmark.bmbm 20 do |x|
#!/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 August 29, 2015 14:13
Data structure where only one thread is allowed to write
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 January 8, 2015 07:35
Create XPath from XML node structure
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 January 6, 2015 16:20
Test different handling of return in lambda, proc and Proc.new
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 December 1, 2014 12:00
How to marshal an object with open stream, file descriptor or other non serializable data
#!/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 October 24, 2014 10:49
Script extracting group information from a text file
#!/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 August 29, 2015 14:01
Test program to investigate effects of buffering and buffer sizes for char based input from file.
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;