Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,753 questions

55,518 answers

573 users

How to remove every N‑th element from an array in Ruby

1 Answer

0 votes
# ------------------------------------------------------------
# A small program demonstrating how to remove every Nth element
# from an Array using clear, expressive Ruby patterns.
# ------------------------------------------------------------

#
# remove_every_nth returns a new array with every Nth element removed.
#
# Ruby arrays use zero‑based indexing, so we check (index + 1) % n != 0
# to keep elements that are *not* in the Nth position.
#
# The variable "size" captures the array length before the loop,
# which avoids repeatedly calling items.size inside the loop.
#
def remove_every_nth(items, n)
  raise ArgumentError, "n must be a positive integer" if n <= 0

  size = items.size          # capture size once
  result = Array.new         # output array

  # Perform a single pass over the array
  for i in 0...size
    result << items[i] if (i + 1) % n != 0
  end

  result
end

#
# Keeping the main execution block small and focused makes the program
# easy to extend. Here we demonstrate the function with a simple example.
#
data = (1..20).to_a   # Example array: numbers 1–20
n = 3                 # Remove every 3rd element

cleaned = remove_every_nth(data, n)

puts "Original: #{data.join(' ')}"
puts "After removing every #{n}-th element: #{cleaned.join(' ')}"




=begin
run:

Original: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After removing every 3-th element: 1 2 4 5 7 8 10 11 13 14 16 17 19 20

=end

 



answered 1 day ago by avibootz
...