D69bd6b89f0c9204eed89de9d7ee4632

Is there a better, shorter and most importantly more beautiful way of doing the same thing?

def randomize_case(string)
  letters = string.split("")

  new_string = ""
  letters.each do |letter|
    new_string += (rand(2)) == 0 ? letter.downcase : letter.upcase
  end

  new_string
end

Refactorings

No refactoring yet !

55502f40dc8b7c769880b10874abc9d0

michal-pochwala.myopenid.com

August 22, 2011, August 22, 2011 08:06, permalink

No rating. Login to rate!

I am beginning with ruby so your comments are welcome.

#my try [ruby]
def randomize_case(string)
  string.each_char.inject(""){ |result,char| result+ ((rand(2)) == 0 ? char.downcase : char.upcase) }
end
B8ba61cc84ecb63c859435be28547dfb

steved

August 22, 2011, August 22, 2011 13:20, permalink

No rating. Login to rate!
def randomize_case(string)
  string.split("").map { |c| (rand(2)) == 0 ? c.downcase : c.upcase  }.join('')
end
A8d3f35baafdaea851914b17dae9e1fc

Adam

August 31, 2011, August 31, 2011 14:18, permalink

No rating. Login to rate!
def randomize_case(string)
  string.gsub(/./) { |char| char.send(rand(2).zero? ? :downcase : :upcase) }
end

Your refactoring





Format Copy from initial code

or Cancel