HomeToolsAbout

Array

Array Element Diffing

Finding included and excluded elements between two arrays.

  • Using a set difference, you can check if one array includes all elements of another.
not_included = [1,2,3] - (1..9).to_a not_included # [] not_included = [1,2,3,'A'] - (1..9).to_a not_included # ["A"]

Use each_slice to chop up array by x number of elements

batch_size = 2 arr.each_slice(batch_size) { |batch| batch*2 } (1..10).each_slice(3) { |a| p a } # outputs below [1, 2, 3] [4, 5, 6] [7, 8, 9] [10]

Grab n-number of elements from beginning or end of array

Use Array.first(x) to grab x-number of elements in the front of the array.

Grabbing from end to front would be Array.last(x).

a = [ "q", "r", "s", "t" ] a.first # "q" a.first(2) # ["q", "r"]
AboutContact