string - Ruby method that uppercases even indexed letters and lowercases odd -
directions:
write method accepts string, , returns same string indexed characters in each word upper cased, , odd indexed characters in each word lower cased. indexing explained 0 based, zero-ith index even, therefore character should upper cased.
the passed in string consist of alphabetical characters , spaces(' '). spaces present if there multiple words. words separated single space(' ').
my code:
(someone please refactor or explain me cleaner/shorter solution)
def weirdcase(string) arr = string.split(' ') arr.map! {|word| char = word.chars char.each_with_index |letter, i| % 2 == 0 ? letter.upcase! : letter.downcase! end } arr.map! {|a| a.push(' ').join('')} x = arr.join('').to_s x[0...-1] end
this 1 way that, using array#cycle create enumerator , string#gsub replace every character in string value upcased or downcased.
def weirdcase(str) enum = [:upcase, :downcase].cycle str.gsub(/./) |s| if s == ' ' enum.rewind s else s.public_send(enum.next) end end end weirdcase "mary had little lamb" #=> "mary had little lamb"
by making gsub
's argument /./
each character in string replaced value returned block, which, if character not space, character either upcased or downcased, depending on symbol generated enumerator enum
, alternates between :upcase
, :downcase
each word.
note that
enum = [:upcase, :downcase].cycle #=> #<enumerator: [:upcase, :downcase]:cycle> enum.next #=> :upcase enum.next #=> :downcase enum.next #=> :upcase
and on. see enumerator#next.
enumerator#rewind needed begin anew alternating of case each word.
one replace s.public_send(enum.next)
with
enum.next == :upcase ? s.upcase : s.downcase
Comments
Post a Comment