Mitch
Mitch

Reputation: 118

Converting even indexed characters in a string to uppercase ruby

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

Upvotes: 1

Views: 1177

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110745

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" 

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118289

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.

Upvotes: 2

sawa
sawa

Reputation: 168239

"foobar".gsub(/(.)(.?)/){$1.upcase + $2.downcase}   # => "FoObAr"
"fooba".gsub(/(.)(.?)/){$1.upcase + $2.downcase}    # => "FoObA"

Upvotes: 2

Related Questions