Skip to content

Instantly share code, notes, and snippets.

@higaki
Created February 9, 2013 10:41
Show Gist options
  • Save higaki/4744825 to your computer and use it in GitHub Desktop.
Save higaki/4744825 to your computer and use it in GitHub Desktop.
#! /usr/bin/env ruby
# -*- coding: utf-8; -*-
RUBY_DESCRIPTION # => "ruby 1.9.3p385 (2013-02-06 revision 39114) [x86_64-darwin10.8.0]"
# Enumerable#map を自作してみよう
# ただし Enumerable#map と Enumerable#map! は使用禁止
module Enumerable
def my_map
unless block_given?
# ブロックがもらえなかったら Enumerator を返す
to_enum __callee__
else
# 空の Array を用意し、
inject([]) do |result, item|
# ブロックの評価結果を追加する
result << yield(item)
end
end
end
end
a = [*0..3] # => [0, 1, 2, 3]
a.map{|i| i * 2} # => [0, 2, 4, 6]
a.my_map{|i| i * 2} # => [0, 2, 4, 6]
i = a.map # => #<Enumerator: [0, 1, 2, 3]:map>
j = a.my_map # => #<Enumerator: [0, 1, 2, 3]:my_map>
i.next # => 0
i.next # => 1
i.next # => 2
i.next # => 3
j.next # => 0
j.next # => 1
j.next # => 2
j.next # => 3
j.next # =>
# ~> -:40:in `next': iteration reached an end (StopIteration)
# ~> from -:40:in `<main>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment