It's GG

Life is simple...

1 note

New proc syntax in 1.9

BEGIN {
  puts "Ruby Version : #{RUBY_VERSION}"
}

succ = ->(x=0) { x + 1 }
p succ.call
p succ.call(2)

successor = Proc.new {|x=0| x + 1}
p successor.call
p successor.call(10)

Output

Ruby Version : 1.9.1
1
3
1
11

But thanks, I will stick with the old syntax!

Filed under ruby snippet

0 notes

Fibers in Ruby 1.9

class Fib
  include Enumerable
  
  def initialize(stop_at)
    @count = 0
    @stop_at = stop_at
    @first, @second = 0, 1
    @fiber = Fiber.new do
      loop do
        @first, @second = @second, @first + @second
        @count += 1
        Fiber.yield @first
      end
    end
  end
  
  def next
    @fiber.resume
  end
  
  def rewind
    @first, @second = 0, 1
  end
  
  def each
    loop do
      @count == @stop_at ? break : yield(self.next)
    end
  end
end

# Print the first 20 fibonacci numbers
Fib.new(20).each do |elem|
  puts elem
end

Output

1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765

Filed under ruby snippet