Created
October 11, 2022 00:30
-
-
Save JoshCheek/f3dcc41baaa60435e9878c123c01899e to your computer and use it in GitHub Desktop.
Checks if the elements of one array are contained by another
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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