Q:

Ruby modify a piece of a string

Totally new to Ruby. This is a simple homework assignment. The secret_code function needs to take in input string and perform the following actions:

In the first block of letters before a space, capitalize all but the first char
Reverse the string

So if the input were "super duper", the output should be "repud REPUs".
I coded the function as follows:
def secret_code(input) 
  input.split(" ").first[1..-1].each_char do |i|
    input[i] = i.upcase
  end
  return input.reverse
end

It passes the unit tests, but I am wondering if there is a better way to code it. Is it possible to avoid using the loop? I tried
return input.split(" ").first[1..-1].upcase.reverse

But that didn't quite work. Any thoughts on how to clean this up are appreciated!

A:

"super duper".sub(/(?<=.)\S+/, &:upcase).reverse

A:

How about this:
def secret_code(input)
  first_space = input.index(' ')
  (input[0] + input[1...first_space].upcase + input[first_space..-1]).reverse
end

Note that in Ruby, the last expression evaluate in a method is always returned, so you can omit the final return.

