双“gsub”多变的
是否可以在 gsub 方法的两个字段中使用变量? 我正在尝试让这段代码工作:
$I = 0
def random_image
$I.to_s
random = rand(1).to_s
logo = File.read('logo-standart.txt')
logo_aleatoire = logo.gsub(/#{$I}/, random)
File.open('logo-standart.txt', "w") {|file| File.puts logo_aleatoire}
$I.to_i
$I += 1
end
提前致谢!
Is it possible to use variables in both fields of the gsub method ?
I'm trying to get this piece of code work :
$I = 0
def random_image
$I.to_s
random = rand(1).to_s
logo = File.read('logo-standart.txt')
logo_aleatoire = logo.gsub(/#{$I}/, random)
File.open('logo-standart.txt', "w") {|file| File.puts logo_aleatoire}
$I.to_i
$I += 1
end
Thanks in advance !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
神奇的线是第二线。
gsub!
函数会就地修改字符串,这与gsub
函数不同,后者会返回一个新字符串并保持第一个字符串不变。gsub!
的单个参数是要匹配的模式。在这里,目标是匹配任何一个或多个数字的字符串 - 这是您要替换的数字。无需循环遍历在每个数字上运行 gsub 的所有可能数字。您甚至可以匹配高达 googol(或更高)的数字,而无需您的程序运行越来越长的时间。gsub!
所采用的块,以编程方式生成替换编号。所以每次,你都会得到一个不同的随机数。这与采用两个参数的更常见的gsub!
形式不同——在任何模式匹配发生之前,该参数会被计算一次,并且所有匹配都将替换为相同的字符串。请注意,这种结构的方式是,每次比赛您都会获得一个新的随机数。所以如果数字307出现两次,它就会变成两个不同的随机数。
如果您想每次将 307 映射到相同的随机数,您可以执行以下操作:
这里,
randomnumbers
是一个散列,可让您查找数字并找到它们对应的随机数。构造哈希时传递的块告诉哈希在找到以前从未见过的数字时要做什么——在这种情况下,生成一个新的随机数,并记住该随机数的映射。因此,gsub!
的块只是要求哈希为其映射数字,而randomnumbers
会在您遇到原始文件中的新数字时负责生成新的随机数。The magic line is the second line.
gsub!
function modifies the string in-place, unlike thegsub
function, which would return a new string and leave the first string unmodified.gsub!
is the pattern to match. Here, the goal is to match any string of one or more digits -- this is the number that you're going to replace. There's no need to loop through all of the possible numbers running gsub on each one. You can even match numbers as high as a googol (or higher) without your program taking longer and longer to run.gsub!
takes is evaluated each time the pattern matches to programmatically generate a replacement number. So each time, you get a different random number. This is different from the more usual form ofgsub!
that takes two parameters -- there the parameter is evaluated once before any pattern matching occurs, and all matches are replaced by the same string.Note that the way this is structured, you get a new random number for each match. So if the number 307 appears twice, it turns into two different random numbers.
If you wanted to map 307 to the same random number each time, you could do the following:
Here,
randomnumbers
is a hash that lets you look up the numbers and find what random number they correspond to. The block passed when constructing the hash tells the hash what to do when it finds a number that it hasn't seen before -- in this case, generate a new random number, and remember what that random number the mapping. Sogsub!
's block just asks the hash to map numbers for it, andrandomnumbers
takes care of generating a new random number when you encounter a new number from the original file.