user3267582
user3267582

Reputation:

Code to display alternating upper and lower-case returns lower-case only?

I am trying to write a function that displays a string as alternating upper and lower case letters.

For example:

str= "My name is ballouta!"
==> My NaMe Is BaLlOuTa!

My code is:

def alt_case
flag = 0
str = ''
self.scan(/./) do |b|
  if flag == 0
    b.upcase ; 
    flag = 1
    str = str + b

  else
    b.downcase
    flag = 0
    str =  str + b

  end #end if

end #end do
str
end #end method

This code returns the string as lower-case ONLY.

Upvotes: 0

Views: 1428

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110685

Edit: I see @bjhaid suggested pretty much the same solution as mine in a comment well before I posted this. I'll leave my answer up for the explanation I've provided.

Now that your question has been answered, let me suggest a way to change your code to make it more Ruby-like:

class String
  def alt_case
    split.map { |w| w.chars.map.with_index{ |s,i|
      i.even? ? s.upcase : s.downcase }.join }.join(' ')
  end
end

"My name is ballouta!".alt_case #=> "My NaMe Is BaLlOuTa!"

Here's how this works:

self           #=> "My name is ballouta!" (default receiver)
a = self.split #=> ["My", "name", "is", "ballouta!"]
b = a.map { |w| w.chars.map.with_index{ |s,i|
      i.even? ? s.upcase : s.downcase }.join }
               #=> ["My", "NaMe", "Is", "BaLlOuTa!"]
b.join(' ')    #=> "My NaMe Is BaLlOuTa!" 

When computing b, consider the case when w => "name":

c = w.chars    #=> ["n", "a", "m", "e"] 
d = c.map.with_index{ |s,i| i.even? ? s.upcase : s.downcase }
               #=> ["N", "a", "M", "e"] 
d.join         #=> "NaMe"

I added this method to the String class only because that's what you've done, but in general I wouldn't recommend that; alt_case(string) would be fine.

Upvotes: 0

sawa
sawa

Reputation: 168121

"My name is ballouta!"
.gsub(/\w/).with_index{|s, i| i.even? ? s.upcase : s.downcase}
# => "My NaMe Is BaLlOuTa!"

Upvotes: 3

sevenseacat
sevenseacat

Reputation: 25029

You're using upcase and downcase, both of which return the altered value (which you are not saving and using).

The in-place alternatives upcase! and downcase! may help you out.

Upvotes: 0

Related Questions