这样说我的节目就是这样:
my_string = "I think we should implement <random_plan> instead of <random_plan>"
def generate_random_plan
#Some code that returns a string that is not the same every time the method is called, involving randomness.
end
puts my_string.gsub("<random_plan>", generate_random_plan)
因此,正如我所写的,它会打印出类似“我认为我们应该实施计划H而不是计划H”的内容。当我真正想要的是gsub
每次执行替换时调用该方法,所以我最终会得到“我认为我们应该实现计划D而不是计划Q”。我有一个偷偷摸摸的怀疑,gsub
方法不是为此而构建的,而且无法完成,所以你能建议最容易实现的方法吗?
答案 0 :(得分:4)
Ruby中的一个基本原则是“如有疑问,请尝试代码块”。事实上,gsub()
接受代码块代替第二个参数的字符串。
这是一个类似于你正在寻找的例子:
'axbxcxdxe'.gsub( 'x' ) { rand(9) }
在irb
中尝试该代码,您将获得x的随机数字:
a0b6c0d3e
替换代码块是一个强大的功能,特别是因为它接收原始匹配的字符串作为参数。作为一个人为的例子,假设您只想将字符串中的元音转换为大写:
def vowelup( s )
s.gsub( /[aeiouy]/ ) { |c| c.upcase }
end
print vowelup( 'Stack Overflow' )
打印:
StAck OvErflOw
JavaScript基本上也具有相同的功能:
function vowelup( s ) {
return s.replace( /[aeiouy]/g, function( c ) {
return c.toUpperCase();
});
}
console.log( vowelup('Stack Overflow') );
答案 1 :(得分:0)
gsub
接受一个块,如果给出,则在每次匹配时调用它。从中返回随机值。
my_string = "I think we should implement <random_plan> instead of <random_plan>"
def generate_random_plan s
plans = ('A'..'Z').to_a
s.gsub('<random_plan>') do
plans.sample # random plan
end
end
generate_random_plan my_string # => "I think we should implement A instead of J"
generate_random_plan my_string # => "I think we should implement Q instead of A"
generate_random_plan my_string # => "I think we should implement Z instead of H"