John John - 4 months ago 7
Ruby Question

Adding Swapcase class to string

Trying to create a method for String class that will return a string swapcased. I have written two different methods

class String
def to_alternating_case
self.swapcase
end
end


The above code works for all strings entered. However if the following code is entered:

class String
def to_alternating_case
self.swapcase!
end
end


Then a string which contains all numbers will return nil. Can someone explain why these behave differently when it comes to string containing only numbers?

Answer

The differences are all in the manual.

String#swapcase!:

Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made. Note: case conversion is effective only in ASCII region.