parker.sikand
parker.sikand

Reputation: 1381

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:

  1. In the first block of letters before a space, capitalize all but the first char
  2. 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!

Upvotes: 3

Views: 209

Answers (5)

Arup Rakshit
Arup Rakshit

Reputation: 118261

You can try the below:

a = "super duper"
p a.gsub(a.split[0...1].join(' '),a.split[0...1].join(' ').capitalize.swapcase).reverse

Output:

"repud REPUs"

Upvotes: 1

DigitalRoss
DigitalRoss

Reputation: 146053

Not necessarily any better, but sure, it can be done without a loop...

def f x
  (b = [(a = x.split)[0].upcase, *a.drop(1)].join(' ').reverse)[-1] = x[0, 1]
  return b
end

Upvotes: 1

sawa
sawa

Reputation: 168071

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

Upvotes: 8

Agis
Agis

Reputation: 33626

s = "super duper"

words = s.split(' ')
words.first[1..-1] = words.first[1..-1].upcase
words.each { |word| word.reverse! }
s = words.reverse.join(' ')
puts s # => repud REPUs

Upvotes: 1

Stuart M
Stuart M

Reputation: 11588

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.

Upvotes: 3

Related Questions