【问题标题】:Simpler way to alternate upper and lower case words in a string在字符串中交替大小写单词的更简单方法
【发布时间】:2021-08-14 14:21:10
【问题描述】:

我最近解决了这个问题,但觉得有一种更简单的方法可以解决。我研究了注入、步进和映射,但不知道如何在这段代码中实现它们。我想使用比现在更少的代码行。我是 ruby​​ 的新手,所以如果答案很简单,我很乐意将它添加到我的工具包中。提前谢谢你。

目标:接受一个句子字符串作为arg,并返回包含大写和小写交替单词的句子

def alternating_case(str)
    newstr = []
    words = str.split
    words.each.with_index do |word, i|
        if i.even?
            newstr << word.upcase
        else
            newstr << word.downcase
        end
    end
    newstr.join(" ")
end

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    您可以通过使用三元条件 (true/false ? value_if_true : value_if_false) 来减少 each_with_index 块中的行数:

    words.each.with_index do |word, i|
      newstr << i.even? ? word.upcase : word.downcase
    end
    

    至于完全不同的方式,您可以逐个字母地迭代初始字符串,然后在点击空格时更改方法:

    def alternating_case(str)
      @downcase = true
      new_str = str.map { |letter| set_case(letter)}
    end
    
    def set_case(letter)
      @downcase != @downcase if letter == ' '
      return @downcase ? letter.downcase : letter.upcase
    end
    

    【讨论】:

    【解决方案2】:

    我们可以通过使用 ruby​​ 的Array#cycle 来实现这一点。

    Array#cycle 返回一个 Enumerator 对象,该对象为枚举的每个元素重复调用块 n 次,如果没有给出或 nil 则永远调用。

    cycle_enum = [:upcase, :downcase].cycle
    #=> #<Enumerator: [:upcase, :downcase]:cycle>
    
    5.times.map { cycle_enum.next }
    #=> [:upcase, :downcase, :upcase, :downcase, :upcase]
    

    现在,使用上面我们可以写成如下:

    word = "dummyword"
    cycle_enum = [:upcase, :downcase].cycle
    word.chars.map { |c| c.public_send(cycle_enum.next) }.join("")
    #=> "DuMmYwOrD"
    

    注意:如果您是 ruby​​ 新手,您可能不熟悉 public_sendEnumberable 模块。您可以使用以下参考资料。

    【讨论】:

    • 定义cycle_enum后,可以写成word.gsub(/./) { |c| c.public_send(cycle_enum.next) }
    猜你喜欢
    • 2018-08-06
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 2013-01-10
    • 2016-09-06
    • 1970-01-01
    • 2021-08-14
    • 2013-10-24
    相关资源
    最近更新 更多