在 Ruby 中,如何生成一长串重复文本? [英] In Ruby how do I generate a long string of repeated text?

查看:22
本文介绍了在 Ruby 中,如何生成一长串重复文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ruby​​ 中快速生成长字符串的最佳方法是什么?这有效,但速度很慢:

What is the best way to generate a long string quickly in ruby? This works, but is very slow:

str = ""
length = 100000
(1..length).each {|i| str += "0"}

我还注意到,创建一个合适长度的字符串,然后将其附加到现有字符串中,达到所需长度的工作速度要快得多:

I've also noticed that creating a string of a decent length and then appending that to an existing string up to the desired length works much faster:

str = ""
incrementor = ""
length = 100000
(1..1000).each {|i| incrementor += "0"}
(1..100).each {|i| str += incrementor}

还有其他建议吗?

推荐答案

str = "0" * 999999

这篇关于在 Ruby 中,如何生成一长串重复文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆