Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created October 11, 2022 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/f3dcc41baaa60435e9878c123c01899e to your computer and use it in GitHub Desktop.
Save JoshCheek/f3dcc41baaa60435e9878c123c01899e to your computer and use it in GitHub Desktop.
Checks if the elements of one array are contained by another
# https://twitter.com/postmodern_mod3/status/1579281378390478849
def contains?(superary, subary)
(0..superary.length-subary.length).any? do |start|
subary.each_index.all? do |offset|
superary[start+offset] == subary[offset]
end
end
end
# true
contains? [], [] # => true
contains? [*1..5], [] # => true
contains? [*1..5], [1] # => true
contains? [*1..5], [1,2] # => true
contains? [*1..5], [*1..5] # => true
contains? [*1..5], [2,3] # => true
contains? [*1..5], [3,4,5] # => true
contains? [*1..5,1,2,3,5,4], [3,5] # => true
# false
contains? [*1..5], [0] # => false
contains? [*1..5], [6] # => false
contains? [*1..5], [3,5] # => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment