summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-enum-ext/mrblib/enum.rb
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2014-03-17 00:04:34 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2014-03-17 00:04:34 +0900
commit55c1942b43b1e62956e6ce1798dc10fe742d617c (patch)
tree5df0f35878f680482a94470b3ac321b319a59970 /mrbgems/mruby-enum-ext/mrblib/enum.rb
parent18bebd3acdea1124b3d192ffc171eb6807d391cf (diff)
downloadmruby-55c1942b43b1e62956e6ce1798dc10fe742d617c.tar.gz
mruby-55c1942b43b1e62956e6ce1798dc10fe742d617c.zip
add Enumerable#first to mruby-enum-ext
Diffstat (limited to 'mrbgems/mruby-enum-ext/mrblib/enum.rb')
-rw-r--r--mrbgems/mruby-enum-ext/mrblib/enum.rb26
1 files changed, 26 insertions, 0 deletions
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb
index f250d39f1..85779ee59 100644
--- a/mrbgems/mruby-enum-ext/mrblib/enum.rb
+++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb
@@ -161,4 +161,30 @@ module Enumerable
h
end
+ NONE = Object.new
+ ##
+ # call-seq:
+ # enum.first -> obj or nil
+ # enum.first(n) -> an_array
+ #
+ # Returns the first element, or the first +n+ elements, of the enumerable.
+ # If the enumerable is empty, the first form returns <code>nil</code>, and the
+ # second form returns an empty array.
+ def first(n=NONE)
+ if n == NONE
+ self.each do |e|
+ return e
+ end
+ return nil
+ else
+ a = []
+ i = 0
+ self.each do |e|
+ break if n<=i
+ a.push e
+ i += 1
+ end
+ a
+ end
+ end
end