ruby-changes:64394
From: Victor <ko1@a...>
Date: Mon, 21 Dec 2020 09:32:50 +0900 (JST)
Subject: [ruby-changes:64394] 5253b9579a (master): Document usage of ArithmeticSequence in Array#slice, and add to NEWS (#3952)
https://git.ruby-lang.org/ruby.git/commit/?id=5253b9579a From 5253b9579a129f66a768dae24bd50a95bab02841 Mon Sep 17 00:00:00 2001 From: Victor Shepelev <zverok.offline@g...> Date: Mon, 21 Dec 2020 02:32:30 +0200 Subject: Document usage of ArithmeticSequence in Array#slice, and add to NEWS (#3952) diff --git a/NEWS.md b/NEWS.md index d88642b..447788b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -149,6 +149,14 @@ Outstanding ones only. https://github.com/ruby/ruby/blob/trunk/NEWS.md#L149 * Array#uniq * Array#* + * Can be sliced with Enumerator::ArithmeticSequence + + ```ruby + dirty_data = ['--', 'data1', '--', 'data2', '--', 'data3'] + dirty_data[(1..).step(2)] # take each second element + # => ["data1", "data2", "data3"] + ``` + * ConditionVariable * ConditionVariable#wait may now invoke the `block`/`unblock` scheduler diff --git a/array.c b/array.c index f4c3e27..ea84473 100644 --- a/array.c +++ b/array.c @@ -1775,11 +1775,22 @@ static VALUE rb_ary_aref2(VALUE ary, VALUE b, VALUE e); https://github.com/ruby/ruby/blob/trunk/array.c#L1775 * a[4..0] # => nil * a[4..-1] # => nil * - * When a single argument +aseq+ is given, - * ...(to be described) - * - * Raises an exception if given a single argument - * that is not an \Integer-convertible object or a \Range object: + * When a single Enumerator::ArithmeticSequence argument +aseq+ is given, + * returns an Array of elements corresponding to the indexes produced by + * the sequence. + * a = ['--', 'data1', '--', 'data2', '--', 'data3'] + * a[(1..).step(2)] # => ["data1", "data2", "data3"] + * + * Unlike slicing with range, if the start or the end of the arithmetic sequence + * is larger than array size, throws RangeError. + * a = ['--', 'data1', '--', 'data2', '--', 'data3'] + * a[(1..11).step(2)] + * # RangeError (((1..11).step(2)) out of range) + * a[(7..).step(2)] + * # RangeError (((7..).step(2)) out of range) + * + * If given a single argument, and its type is not one of the listed, tries to + * convert it to Integer, and raises if it is impossible: * a = [:foo, 'bar', 2] * # Raises TypeError (no implicit conversion of Symbol into Integer): * a[:foo] diff --git a/enumerator.c b/enumerator.c index 68cfc2b..fe5f054 100644 --- a/enumerator.c +++ b/enumerator.c @@ -3333,6 +3333,9 @@ enumerator_plus(VALUE obj, VALUE eobj) https://github.com/ruby/ruby/blob/trunk/enumerator.c#L3333 * that is a representation of sequences of numbers with common difference. * Instances of this class can be generated by the Range#step and Numeric#step * methods. + * + * The class can be used for slicing Array (see Array#slice) or custom + * collections. */ VALUE -- cgit v0.10.2 -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/