29 November 2012

ruby day three

by mo


We completed the sorting exercises and discussed comparers. We discussed iterators and got started with meta programming.

sorting

  def sort_using(comparison = nil, &block)
    comparer = block_given? ? block : comparison
    each.to_a.sort {|x,y| comparer.call(x,y)}
  end

  class DefaultComparer
    def compare(x,y)
      x <=> y
    end
  end

  class RankedComparer
    include ComparisonBehaviours
    def initialize(items)
      @items = items
    end
    def compare(x,y)
      @items.index(x) <=> @items.index(y)
    end
  end

  class ReverseComparer
    include ComparisonBehaviours

    def initialize(inner)
      @inner = inner
    end

    def compare(x,y);- @inner.compare(x,y);end
  end

  class SymbolicComparer
    include ComparisonBehaviours

    def initialize(field,real_comparison = DefaultComparer.new)
      @field = field
      @real_comparison = real_comparison
    end

    def compare(x,y)
      @real_comparison.compare(x.send(@field),y.send(@field))
    end
  end

iterators

  class Enumerator
    def deferred_select(&condition)
      Enumerator.new do |yielder|
        self.each do |value|
          yielder.yield value if condition.call(value)
        end
      end
    end
  end

  numbers = Enumerator.new do|yielder|
    number = 1
    loop do
      yielder.yield number
      number += 1
    end
  end

  p numbers.deferred_select{|item| item < 10}.take(5)

meta programming

  • define_method
  • instance_variable_get
  • instance_variable_set
  class Hash
    def to_strong_object
      target = Object.new
      add_attributes_to target
      target
    end

    def add_attributes_to(target)
      property_accessor_modules.each do|the_mixin|
        target.extend(the_mixin)
      end
    end

    def reader_module(values)
      initialized = {}
      Module.new do
        values.each do|name,value|
          define_method name do
            value
          end
        end
      end
    end

    def writer_module(values)
      Module.new do
        values.each_key do|name|
          define_method "#{name}=" do |new_value|
            values[name] = new_value
          end
        end
      end
    end

    def property_accessor_modules
      [reader_module(self),writer_module(self)]
    end
  end

  class Person
    def initialize(values = Hash.new(nil))
      values.add_attributes_to self
    end
  end

Use rescue time or time snapper to find out where your time is being spent. Low tolerance for wasted time.

Choose to be your best everyday.

💎