2013-04-07 56 views
3

完全陌生的紅寶石。這是一項簡單的家庭作業。該secret_code功能需要採取輸入字符串並執行以下操作:紅寶石修改一塊串

  1. 在字母的第一塊空間之前,利用所有,但第一個字符
  2. 字符串逆向

所以如果輸入是「super duper」,則輸出應該是「repu REPUs」。

我所編碼的功能如下:

def secret_code(input) 
    input.split(" ").first[1..-1].each_char do |i| 
    input[i] = i.upcase 
    end 
    return input.reverse 
end 

它通過單元測試,但我想知道是否有更好的方式來編寫的。是否有可能避免使用循環?我試過

return input.split(" ").first[1..-1].upcase.reverse 

但是這並不奏效。有關如何清理這個問題的任何想法,我都很感激!

+0

什麼是你期望的輸出? – 2013-04-07 17:51:13

+2

@RubyLovely他告訴過你。閱讀問題。 – matt 2013-04-07 17:52:07

+0

請參閱問題。如果輸入的是「這是輸入」時,輸出應該是「tupni SI SIHT」 – 2013-04-07 17:52:16

回答

3

如何:

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

注意,在Ruby中,最後的表達的方法評價總是返回,這樣你就可以忽略最後的return

+0

啊聰明,我喜歡它 – 2013-04-07 17:58:43

+0

是好編碼風格省略回報? – 2013-04-07 18:00:07

+0

見明確的'return'這裏的討論:http://stackoverflow.com/questions/1023146/is-it-good-style-to-explicitly-return-in-ruby – 2013-04-07 18:00:49

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

+1爲正則表達式;) – 2013-04-07 18:04:04

1
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 
1

不一定更好,但肯定的是,它可以在不循環完成了...

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

你可以試試下面的:

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

輸出:

"repud REPUs"