summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-array-ext/mrblib/array.rb
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2014-03-28 23:21:42 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2014-03-28 23:21:42 +0900
commit7d413b7043d905dda432d9703c4612ac1bb4b612 (patch)
tree4016272509d2a3dbc575f8a02ab77a2c648fc151 /mrbgems/mruby-array-ext/mrblib/array.rb
parent97f22c9516c2fdf2c0dc93099e20fc110ac9456d (diff)
parente8cb971bbbdb2f6dee0628f950c6b8094cb5f09d (diff)
downloadmruby-7d413b7043d905dda432d9703c4612ac1bb4b612.tar.gz
mruby-7d413b7043d905dda432d9703c4612ac1bb4b612.zip
Merge branch 'master' of github.com:mruby/mruby
Diffstat (limited to 'mrbgems/mruby-array-ext/mrblib/array.rb')
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb41
1 files changed, 41 insertions, 0 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb
index d29aef325..06b350e28 100644
--- a/mrbgems/mruby-array-ext/mrblib/array.rb
+++ b/mrbgems/mruby-array-ext/mrblib/array.rb
@@ -213,4 +213,45 @@ class Array
end
self
end
+
+ NONE=Object.new
+ ##
+ # call-seq:
+ # ary.fetch(index) -> obj
+ # ary.fetch(index, default) -> obj
+ # ary.fetch(index) { |index| block } -> obj
+ #
+ # Tries to return the element at position +index+, but throws an IndexError
+ # exception if the referenced +index+ lies outside of the array bounds. This
+ # error can be prevented by supplying a second argument, which will act as a
+ # +default+ value.
+ #
+ # Alternatively, if a block is given it will only be executed when an
+ # invalid +index+ is referenced. Negative values of +index+ count from the
+ # end of the array.
+ #
+ # a = [ 11, 22, 33, 44 ]
+ # a.fetch(1) #=> 22
+ # a.fetch(-1) #=> 44
+ # a.fetch(4, 'cat') #=> "cat"
+ # a.fetch(100) { |i| puts "#{i} is out of bounds" }
+ # #=> "100 is out of bounds"
+ #
+
+ def fetch(n=nil, ifnone=NONE, &block)
+ warn "block supersedes default value argument" if n != nil && ifnone != NONE && block
+
+ idx = n
+ if idx < 0
+ idx += size
+ end
+ if idx < 0 || size <= idx
+ return block.call(n) if block
+ if ifnone == NONE
+ raise IndexError, "index #{n} outside of array bounds: #{-size}...#{size}"
+ end
+ return ifnone
+ end
+ self[idx]
+ end
end