Ruby: How to replace odd/even occurrences in a string

input = AA-AA-AA-AA-AA-AA

How do I

  • Replace odd (1st, 3rd, 5th) occurrence with :
  • Replace even (2nd, 4th) occurrence with .

  • sqlite3-ruby gem: Failed to build gem native extension
  • Selenium WebDriver analyze large collection of links quickly
  • compare array of hashes and print expected & actual results
  • Is it possible to sort a list of objects depending on the individual object's response to a method?
  • ActiveRecord select except columns
  • How can I use “nu install …” to install nhibernate 3 alpha?
  • RUBY/WATIR/RASTA: Pass the value from the excel/rasta to an array in Ruby?
  • Why does “gem install passenger” fail with “undefined method `join' for nil:NilClass”?
  • 4 Solutions collect form web for “Ruby: How to replace odd/even occurrences in a string”

    input.gsub("-").with_index(1){|_, i| i.odd? ? ":" : "."}
    # => "AA:AA.AA:AA.AA:AA"
    

    Here’s one way, although its not the one-liner you’re probably looking for:

    input = 'AA-AA-AA-AA-AA-AA'
    input.count('-').times do |i|
      replacement = i.even? ? ':' : '.'
      input.sub!('-', replacement)
    end
    input
    # => "AA:AA.AA:AA.AA:AA"
    
    input = "AA-AA-AA-AA-AA-AA".gsub("AA-AA", ":-.")
    

    perhaps?

    count= 0
    input.gsub!(/\-/) do |s|
      count+= 1; s= count% 2== 0 ? '.' : ':'
    end
    
    Ruby is the best programming language in the world - Ruby on Rails.