【问题标题】:Appending a string to the `puts` output将字符串附加到“puts”输出
【发布时间】:2013-01-08 14:11:02
【问题描述】:

我正在构建一个 gem,它将一个特定的字符串附加到每个 puts 输出。用例可能如下所示:

string_to_append = " hello world!"
puts "The web server is running on port 80"
# => The web server is running on port 80 hello world!

我不知道该怎么做。它的伪代码可能是这样的:

class GemName
  def append
    until 2 < 1
        if puts_is_used == true
            puts string << "hello world!"
        else
            puts ""
        end
    end
  end
end

非常感谢任何有关如何做到这一点的最佳方法的见解。

【问题讨论】:

    标签: ruby concatenation puts


    【解决方案1】:

    这可以通过别名轻松完成。我想说这是装饰方法的一个非常常见的成语。

    # "open" Kernel module, that's where the `puts` lives.
    module Kernel
      # our new puts
      def puts_with_append *args
        new_args = args.map{|a| a + ' hello world'}
        puts_without_append *new_args
      end
    
      # back up name of old puts
      alias_method :puts_without_append, :puts
    
      # now set our version as new puts
      alias_method :puts, :puts_with_append
    end
    
    puts 'foo'
    # >> foo hello world
    
    # it works with multiple parameters correctly
    puts 'bar', 'quux'
    # >> bar hello world
    # >> quux hello world
    

    【讨论】:

    • 哇,就像一个魅力 - 谢谢!我对需要为 puts_without_append 起别名(即备份旧的 puts)感到有点困惑。我尝试了不带“puts_without_append”(仅使用“puts”)的 puts_with_append 方法,只是为了好玩。所以'把 args.map{|a| a + 'hello world'}' 而不是 'puts_without_append args.map{|a| a + 'hello world'}' 但我得到 'TypeError: can't convert String into Array'。不知道为什么?只是好奇...再次感谢!
    • @dougiebuckets:如果你不备份原始的puts,你将如何调用它并附加一个字符串?
    猜你喜欢
    • 2016-12-15
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多