Created
September 21, 2010 12:10
-
-
Save morganp/589581 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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