Thursday, November 8, 2012

Ruby 2.0 new feature : Refinements

In previous article, I wrote the ruby code with "monkey-patching". But, since ruby 2.0, there are better way to do it. It is "Refinements".
require 'singleton'

# Fibonacci as Singleton class
class Fibonacci < Enumerator
  include Singleton

  def initialize
    super { |y|
      a = 0
      b = 1
      loop do
        y << a
        a, b = b, a + b
      end
    }
  end
end

# define a refinement
module Nth
  refine Enumerator do
    def nth(n)
      self.take(n+1).find.with_index { |elem, i| i == n }
    end
  end
end

begin
  # there are no additional methods
  puts Fibonacci.instance.lazy.nth(100)
rescue => e
  puts e
end

#using refinments
using Nth

begin
  # there is an additional method
  puts Fibonacci.instance.lazy.nth(100)
rescue => e
  puts e
end

$ cd /c/ruby-2.0.0
$ ./bin/ruby ~/fibonacci.rb
undefined method `nth' for #<Enumerator::Lazy:0x26430d8>
354224848179261915075

No comments:

Post a Comment