Main
Ruby Snippets

Significant digits.


def sig_digits(n)
    exp = (n == 0) ? 0 : Math.log10(n.abs).to_i
    mag = exp/3

    mant = n.to_f/10**(mag*3)
    post = ['', 'K', 'M', 'B'][mag]
    sig = 2 - (exp%3)

    sprintf("%.#{sig}f%s", mant, post)
end

[0, 3, 10, 999, 1000, 9990, -1, -1000].each{|n| puts "#{n} -> #{sig_digits(n)}"}

#0 -> 0.00
#3 -> 3.00
#10 -> 10.0
#999 -> 999
#1000 -> 1.00K
#9990 -> 9.99K
#-1 -> -1.00
#-1000 -> -1.00K

Recursive composition using blocks.


module RecursiveBuilder
    def self.append_features(mod)
        puts "adding to #{mod}" 
        def mod.new(*args)
            args << yield if block_given?
            return super(*args)
        end

        super
    end
end

class ListNode
    include RecursiveBuilder

    def initialize(obj, child)
        @obj = obj
        @child = child
    end

    def to_s
        "#{@obj} #{@child}" 
    end
end

# pass object in place
# this makes you build it backwards
a = ListNode.new('lincoln', nil)
puts ListNode.new('abraham', a)

# you could do this...
puts ListNode.new('abraham',
    ListNode.new('lincoln', nil)
)

# but using a block lets you do calculations in the same scope
puts ListNode.new('abraham') {
    str = ['l', 'i', 'n', 'c', 'o', 'l', 'n'].join
    ListNode.new(str, nil)
}

Template.


# code...