Добавление строки к выводу `put`

Я строю драгоценный камень, который будет добавлять определенную строку к каждому 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

Любое понимание лучшего подхода относительно того, как это сделать, очень ценится.

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
Другие вопросы по тегам