ruby 从标准快速读取 [英] ruby fast reading from std

查看:54
本文介绍了ruby 从标准快速读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 STDIN 读取 1000000 个字符(整数)并将其拆分为一个字符整数(不是字符串)数组的最快方法是什么?

What is the fastest way to read from STDIN a number of 1000000 characters (integers), and split it into an array of one character integers (not strings) ?

123456 > [1,2,3,4,5,6]

推荐答案

这应该相当快:

a = []
STDIN.each_char do |c|
  a << c.to_i
end

尽管一些粗略的基准测试表明这个 hackish 版本要快得多:

although some rough benchmarking shows this hackish version is considerably faster:

a = STDIN.bytes.map { |c| c-48 }

这篇关于ruby 从标准快速读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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