如何在 Ruby 变量参数中使用带有"#{...}"?



我想要一个这样的方法:

def process(text, *parameters)
new_text = ...
end

其中使用调用函数

process("#{a} is not #{b}", 1, 2)

导致new_text1 is not 2并使用调用函数

process("#{a} does not exist", 'x')

导致CCD_ 3为CCD_。

或者使用替代方式而不是使用"#{...}"(例如#1、#2(来传递填充/替换的参数的字符串。

你可以这样做:

def format(text, *args)
text % args
end
format("%s is not %s", 1, 2)
# => "1 is not 2"
format("%s does not exist", 'x')
# => "x does not exist"

参见String#%Kernel#sprintf

因为上面的方法在内部使用String#%,所以直接使用String#%实际上比将其包装成另一种方法更短:

"%s is not %s" % [1, 2]
# => "1 is not 2"
"%s does not exist" % 'x'
# => "x does not exist"

请注意,在本例中,必须将多个参数作为数组传入。

最新更新