Skip to main content
edited tags
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
Source Link

Transfer the format of an old string to a new string

First, I've extended the String class to detect uppercase and lowercase characters:

class String

    def is_uppercase?
         self == self.upcase    
    end

    def is_lowercase?
        self == self.downcase
    end

end

I then use these instance methods to fulfil my main goal of transferring the format of an old string to a new string:

def maintain_format(instring, outstring)         
      instring_array = instring.split(//)
      outstring_array = outstring.split(//)

      both_arrays = instring_array.zip(outstring_array)
      
      both_arrays.each do |character|
        if character[0] == nil || character[0].is_lowercase?
          character[1].downcase! if character[1]
        elsif character[0].is_uppercase?
          character[1].upcase! if character[1]
        end
     end
      
     outstring_array.join("")
end

 

It works well and does exactly what I want:

2.0.0p247 :002 > maintain_format('jimmy','Jam')
 => "jam" 
2.0.0p247 :003 > maintain_format('Jimmy','xam')
 => "Xam" 
2.0.0p247 :004 > maintain_format('realLylongname','shorter')
 => "shorTer" 
2.0.0p247 :005 > maintain_format('rSeHorteR','muchmuchmuchlongerfoos')
 => "mUcHmuchMuchlongerfoos" 

However, what I love about ruby is how it is sort self-documenting if you use sensible variable and method names and hash keys. With this code it is a bit hard to follow regarding the 1character[0] character[1]` stuff. I attempting it with hashes but got in a bit of a mess. How would you tackle this problem?

Also interested in any ruby tricks to make this take up less lines.

Note this is part of a rails project, so all rails methods are available to me.