summaryrefslogtreecommitdiff
path: root/array.rb
diff options
context:
space:
mode:
authorKoichi Sasada <ko1@atdot.net>2023-03-10 01:33:00 +0900
committerKoichi Sasada <ko1@atdot.net>2023-03-23 14:03:12 +0900
commit0112a5b3423ddb2ddf46c4392f23f9b75128568e (patch)
tree388f54d8dbd34f3dfa96d02ffc37b421fa29e6a4 /array.rb
parentc9fd81b860b5ec193ba57c73c740955937452497 (diff)
downloadruby-0112a5b3423ddb2ddf46c4392f23f9b75128568e.tar.gz
`Array#first` and `Array#last` in Ruby
Diffstat (limited to 'array.rb')
-rw-r--r--array.rb26
1 files changed, 26 insertions, 0 deletions
diff --git a/array.rb b/array.rb
index b9fa9844e6..728438f558 100644
--- a/array.rb
+++ b/array.rb
@@ -66,4 +66,30 @@ class Array
Primitive.ary_sample(random, n, ary)
end
end
+
+ def first n = unspecified = true
+ if Primitive.mandatory_only?
+ Primitive.attr! :leaf
+ Primitive.cexpr! %q{ ary_first(self) }
+ else
+ if unspecified
+ Primitive.cexpr! %q{ ary_first(self) }
+ else
+ Primitive.cexpr! %q{ ary_take_first_or_last_n(self, NUM2LONG(n), ARY_TAKE_FIRST) }
+ end
+ end
+ end
+
+ def last n = unspecified = true
+ if Primitive.mandatory_only?
+ Primitive.attr! :leaf
+ Primitive.cexpr! %q{ ary_last(self) }
+ else
+ if unspecified
+ Primitive.cexpr! %q{ ary_last(self) }
+ else
+ Primitive.cexpr! %q{ ary_take_first_or_last_n(self, NUM2LONG(n), ARY_TAKE_LAST) }
+ end
+ end
+ end
end