Q:

How to convert lowercase string to uppercase and vice versa?

I am trying to write a program which converts all uppercase  characters in a string to lowercase and lowercase characters to uppercase.For example if the string is "abcdE", it will return after coversion "ABCDe".
This is what I have tried so far
class String
    def is_upper?
        self == self.upcase
    end

    def is_lower?
        self == self.downcase
    end
end

s = gets.chomp

if s.length <= 100
    a = s.split(//)
    b, c = Array.new
    a.each do |m|
        if m.is_upper? 
            b.push(m.downcase)
        end
        if m.is_lower?
            b.push(m.upcase)
        end
    end
    c = b.join
end

However I can assess that this program is very erroneous.
I am still a novice learner. So forgive me if my solution program is very wrong.Please help me to find a correct and easier solution.

A:

No need to invent the wheel again.
There is already a method named swapcase in ruby to accomplish this.
For ex-
"Hello".swapcase          #=> "hELLO"
"cYbEr_PuNk11".swapcase   #=> "CyBeR_pUnK11"

You can find more details here-
http://ruby-doc.org/core-2.2.0/String.html#method-i-swapcase

A:

As another pointed out, swapcase already exists, but I suspect it's something you're meant to implement on your own
Here's a functional approach
class String
  def is_upper?
    self == self.upcase
  end

  def is_lower?
    self == self.downcase
  end

  def head
    self[0]
  end

  def tail
    self[1..-1]
  end

  def swapcase
    if empty?
      ""
    elsif head.is_lower?
      head.upcase + tail.swapcase
    elsif head.is_upper?
      head.downcase + tail.swapcase
    else
      head + tail.swapcase
    end
  end
end

puts "abcdE".swapcase
#=> ABCDe

The looping pattern in swapcase is pretty obnoxious and should be decomposed out into a generic function
class String
  def is_upper?
    self == self.upcase
  end

  def is_lower?
    self == self.downcase
  end

  def head
    self[0]
  end

  def tail
    self[1..-1]
  end

  def map &f
    if empty?
      ""
    else
      yield(head) + tail.map(&f)
    end
  end

  def swapcase
    map do |x|
      if x.is_lower?
        x.upcase
      elsif x.is_upper?
        x.downcase
      else
        x
      end
    end
  end
end

It works the same but swapcase is a lot nicer now
puts "abcdE".swapcase
#=> ABCDe

