DEV Community

Discussion on: Daily Challenge #34 - WeIrD StRiNg CaSe

Collapse
 
tanguyandreani profile image
Tanguy Andreani • Edited

Ruby solution. Doesn’t use modulo.

Works with the strange edge case. Also sorry typed on tablet.

str = "Weird ,string case."

class << str
  def to_weird_case
    String.new.tap do |s|
      i = 0

      while i < self.length
        # work out with edge case
        if self[i] =~ /[^a-zA-Z]/
          s << self[i]
          i += 1
          next
        end

        # we add to_s because we may be out of bounds;
        # that way we get the empty string instead of nil
        # and an exception
        s << self[i].to_s.upcase
        s << self[i + 1].to_s.downcase
        i += 2
      end
    end
  end
end

str.to_weird_case