`Array # index` cannot be searched from the middle,` String # index` can be

Environment: Ruby 2.7.1

Reference manual:


For example, consider "find an index that is 1 from an array where each element consists of only 0s and 1s and do something". If you just want to find it, you can do it with each_with_index etc., but if it is a complicated process such as rewriting the original array (which may affect the subsequent search), you need to do your best with a loop statement.

In the case of Ruby, you can specify the position with ** Array # index ** without looping the index. However, this has its drawbacks: ** It cannot be searched from the continuation of the last time **.

seq = [1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1]

i = -1
while (i = seq.index(1, i + 1))
	#Complex processing that requires i
	p i
end
#=> ArgumentError (wrong number of arguments (given 2, expected 0..1))

But ** if it's a string, you can **.

seq = [1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1].map(&:chr).join

i = -1
while (i = seq.index(1.chr, i + 1))
	#Complex processing that requires i
	p i
end
#=> 0 2 4 5 6 7 11 14

The same applies to #rindex, which searches in reverse order.


When changing an array to a character string and searching with # index, there are the following features.

[^ scp]: Also note the possibility that numbers in a certain range cannot be converted to characters, such as in the Unicode surrogate pair area → 0xD800.chr ('UTF-8')

Recommended Posts

`Array # index` cannot be searched from the middle,` String # index` can be
The org.junit.jupiter.api package cannot be found.
[Rails] Rails new cannot be done from Docker
Deletes after the specified character from the character string