Skip to content

Instantly share code, notes, and snippets.

@onigra
Last active August 29, 2015 14:04
Show Gist options
  • Save onigra/c515e1405eb8f46ff279 to your computer and use it in GitHub Desktop.
Save onigra/c515e1405eb8f46ff279 to your computer and use it in GitHub Desktop.

Array#Indexes

arrayから引数に該当するindexの位置を取得してarrayで返す

require 'indexes'

[1, 2, 3, 1, 2].indexes 1

#=> [0, 3]

["foo", "bar", "baz", "foo", "baz", "foo"].indexes "foo"

#=> [0, 3, 5]

["foo", 1, 2, "foo", 3, "foo"].indexes { |i| i.class == String }

#=> [0, 3, 5]

Array#slice_indexes

引数に該当する要素から次の該当する要素までを取得してarrayで返す

require 'indexes'

[1, 2, 3, 1, 2].slice_indexes 1

#=> [[1, 2, 3], [1, 2]]

["foo", "bar", "baz", "foo", "baz", "foo"].slice_indexes "foo"

#=> [["foo", "bar", "baz"], ["foo", "baz"], ["foo"]]

["foo", 1, 2, "foo", 3, "foo"].slice_indexes { |i| i.class == String }

#=> [["foo", 1, 2], ["foo", 3], ["foo"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment