【问题标题】:Ruby modify a piece of a stringRuby修改一段字符串
【发布时间】:2013-03-29 17:46:22
【问题描述】:

对 Ruby 来说是全新的。这是一个简单的家庭作业。 secret_code 函数需要接受输入字符串并执行以下操作:

  1. 在空格前的第一个字母块中,除第一个字符以外的所有字母都大写
  2. 反转字符串

所以如果输入是“super duper”,那么输出应该是“repud 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

但这并不完全奏效。任何关于如何清理它的想法都非常感谢!

【问题讨论】:

  • 你的预期输出是什么?
  • @RubyLovely 他告诉过你。阅读问题。
  • 参考问题。如果输入是“this is input”,则输出应该是“tupni si SIHt”

标签: ruby string


【解决方案1】:
"super duper".sub(/(?<=.)\S+/, &:upcase).reverse

【讨论】:

    【解决方案2】:

    这个怎么样:

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

    请注意,在 Ruby 中,始终返回方法中的最后一个表达式评估,因此您可以省略最后的 return

    【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

      【解决方案4】:

      不一定更好,但可以肯定的是,它可以在没有循环的情况下完成......

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

      【讨论】:

        【解决方案5】:

        您可以尝试以下方法:

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

        输出:

        "repud REPUs"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-26
          • 2014-05-30
          • 2018-04-10
          • 2021-10-22
          • 1970-01-01
          相关资源
          最近更新 更多