0

我正在构建一个 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

非常感谢您对有关如何执行此操作的最佳方法的任何见解。

4

1 回答 1

4

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

# "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
于 2013-01-08T14:19:18.000 回答