【发布时间】:2019-04-30 20:29:18
【问题描述】:
假设我想puts大量字符串大写,但为了简洁,我想每次都写puts(string)而不是puts(string.upcase)。
有没有办法让我重新定义puts仅在一个块内,像这样?
# This will puts as normal
puts "abc"
# => abc
# This will puts an upcased string, but it's too verbose
puts "abc".upcase
# => ABC
# I want to do something like this, which will override the puts method for code run within the block
def always_upcase_strings(&block)
def puts(string)
super(string.upcase)
end
end
always_upcase_strings do
puts "abc"
puts "def"
puts "ghi"
end
puts "xyz"
# => ABC
# => DEF
# => GHI
# => xyz
我上面的例子被简化了——在我的例子中我没有使用puts,而是我自己编写的一个方法。
【问题讨论】:
标签: ruby