Skip to content

Instantly share code, notes, and snippets.

@morganp
Created September 21, 2010 12:10
Show Gist options
  • Save morganp/589581 to your computer and use it in GitHub Desktop.
Save morganp/589581 to your computer and use it in GitHub Desktop.
#Ruby mixin Enumerable implement each:
# hey presto you have .map (but not .map!)
class Core
include Enumerable
attr_reader :name, :data
def initialize( name, data )
@name = name
@data = data
end
# Mixin in .map
# http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html
# Deligating each method from
# http://snippets.dzone.com/posts/show/8247
def each( &blk )
@data.each( &blk )
end
def map!( &blk )
@data.map!( &blk )
end
def fibUpTo(max)
i1, i2 = 1, 1 # parallel assignment
while i1 <= max
yield i1
i1, i2 = i2, i1+i2
end
end
# Adding function to take param and block
def map_row( id )
val = []
@data[id].each do |cell|
val << yield( cell )
end
return val
#@data[id].map( yield )
end
def map_row!( id, &blk)
@data[id] = map_row( id, &blk )
end
end
require 'pp'
a = Core.new( 'dave', [[1,2],[3,4]] )
b= a.map_row(0) { |f| f+1 }
pp b
pp a
a.map_row!(0) { |f| f+1 }
pp a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment