Skip to content

Instantly share code, notes, and snippets.

#! ruby19
require 'date'
class EndlessEnum
include Enumerable
def initialize(x, method = :succ)
@x = x
@method = method
# This class works as a proxy for an instance
# and presents it as Hash.
class InstanceHash
include Enumerable
def initialize(obj, default_val = nil, &default_proc)
@obj = obj
@default = default_val
@default_proc = default_proc || lambda {|h,k| @default}
end
class Module
def attr_with_default(name, default = nil, &init)
n = "@#{name}"
define_method name do
instance_variable_get(n) || (init ? init.call(self) : default)
end
attr_writer name
end
18:00:04 Temp$ allruby sc.rb
CYGWIN_NT-5.1 padrklemme1 1.7.5(0.225/5/3) 2010-04-12 19:07 i686 Cygwin
========================================
ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin]
Rehearsal ----------------------------------------------
scan 2.766000 0.000000 2.766000 ( 2.786000)
scan ++ 4.656000 0.000000 4.656000 ( 4.668000)
scan re 2.688000 0.000000 2.688000 ( 2.696000)
scan re ++ 4.531000 0.000000 4.531000 ( 4.547000)
while 1.094000 0.000000 1.094000 ( 1.135000)
@rklemme
rklemme / nested_each.rb
Created July 1, 2010 09:02
Toy example of simpler loop nesting
11:01:47 Temp$ ./nested_each.rb
[["foo\n", "bar", "dummy"], ["another\nline", "ends", "now\nor not?"]]
Now the test...
"foo\n"
"bar"
"dummy"
"another\n"
"line"
#!/bin/env ruby19
Num = Struct.new :pre, :val do
def succ
self.class.new pre, val.succ
end
def to_s; "#{pre}#{val}" end
def inspect; "#{self.class.name}(#{self})" end
@rklemme
rklemme / html-extract.rb
Created October 19, 2010 20:11
Extract piece of an HTML fragment with Nokogiri
#!/bin/env ruby19
require 'nokogiri'
# Nokogiri should have this as well
REPL = {
'&lt;' => '<',
'&le;' => '<=',
'&gt;' => '>',
'&ge;' => '>=',
@rklemme
rklemme / node.rb
Created October 21, 2010 07:52
Example tree implementation
require 'pp'
Node = Struct.new :value, :parent, :children do
def initialize(value = nil, parent = nil)
self.value = value
self.children = []
yield self if block_given?
end
def add(child)
@rklemme
rklemme / EncodingTest.java
Created November 28, 2010 17:12
Print out all converted code points
package enc;
public class EncodingTest {
public static void main(String[] args) {
boolean lastDefined = !Character.isDefined(0);
int lastStart = -1;
for (int i = Character.MIN_CODE_POINT; i <= Character.MAX_CODE_POINT; ++i) {
final boolean def = Character.isDefined(i);
@rklemme
rklemme / sort-1.rb
Created December 2, 2010 14:22
Change order of elements so labels precede their values
# test whether the given element is a month label
def is_label(o)
String === o
end
# exchange values at positions
def swap(arr, i, j)
# not using parrallel assignment since
# we want to avoid all the fancy stuff
x = arr[i]