Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
用 Ruby 计算 JSON 文件中单词的最佳方法是什么?
该scan方法将完成这项工作,但会花费大量内存。
scan
尝试块版本scan:
count = 0 json_string.scan(/\w+/) { count += 1 }
如果您不想一次将整个文件读入内存:
count = 0 File.new("test.json").each_line do |line| line.scan(/\w+/) { count += 1 } end
当然,这假设您的 JSON 文件已格式化(例如,使用 prettify_json.rb。)显然,如果所有内容都在一行上,则效果不会很好。