Search code examples
rubyjsoncountwords

Counting words in JSON file with Ruby


What is the best way to count words in a JSON file with Ruby?

The scan method will do the job but spends a lot of memory.


Solution

  • Try the block version of scan:

    count = 0
    json_string.scan(/\w+/) { count += 1 }
    

    If you don't want to read the whole file into memory at once:

    count = 0
    File.new("test.json").each_line do |line|
      line.scan(/\w+/) { count += 1 }
    end
    

    This assumes of course that your JSON file is formatted (using prettify_json.rb, for instance.) It won't do much good if everything is on a single line, obviously.