1

I need to convert all the even indexed characters in a string to become uppercase, while the odd indexed characters stay lowercase. I've tried this, but it keeps failing and I'm not sure why. I'd appreciate some help!

 for i in 0..string.length if (i % 2) == 0 string[i].upcase else string[i].downcase end end 
0

3 Answers 3

2
"foobar".gsub(/(.)(.?)/){$1.upcase + $2.downcase} # => "FoObAr" "fooba".gsub(/(.)(.?)/){$1.upcase + $2.downcase} # => "FoObA" 
Sign up to request clarification or add additional context in comments.

Comments

2

There you go:

string = "asfewfgv" (0...string.size).each do |i| string[i] = i.even? ? string[i].upcase : string[i].downcase end string # => "AsFeWfGv" 

We people don't use for loop usually, that's why I gave the above code. But here is correct version of yours :

string = "asfewfgv" for i in 0...string.length # here ... instead of .. string[i] = if (i % 2) == 0 string[i].upcase else string[i].downcase end end string # => "AsFeWfGv" 

You were doing it correctly, you just forgot to reassign it the string index after upcasing or downcasing.

1 Comment

I appreciate your help but for some reason this isn't working for me
0

You have two problems with your code:

  • for i in 0..string.length should be for i in 0...string.length to make the last character evaluated string[string.length-1], rather than going past the end of the string (string[string.length]); and
  • string[i] must be an L-value; that is, you must have, for example, string[i] = string[i].upcase.

You can correct your code and make it more idiomatic as follows:

string = "The cat in the hat" string.length.times do |i| string[i] = i.even? ? string[i].upcase : string[i].downcase end string #=> "ThE CaT In tHe hAt" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.