Method: File.wc

Defined in:
lib/ptools.rb

.wc(filename, option = 'all') ⇒ Object

With no arguments, returns a four element array consisting of the number of bytes, characters, words and lines in filename, respectively.

Valid options are ‘bytes’, ‘characters’ (or just ‘chars’), ‘words’ and ‘lines’.

Raises:

  • (ArgumentError)


334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/ptools.rb', line 334

def self.wc(filename, option = 'all')
  option = option.downcase
  valid = %w[all bytes characters chars lines words]

  raise ArgumentError, "Invalid option: '#{option}'" unless valid.include?(option)

  n = 0

  if option == 'lines'
    File.foreach(filename){ n += 1 }
    n
  elsif option == 'bytes'
    File.open(filename) do |f|
      f.each_byte{ n += 1 }
    end
    n
  elsif %w[characters chars].include?(option)
    File.open(filename) do |f|
      n += 1 while f.getc
    end
    n
  elsif option == 'words'
    File.foreach(filename) do |line|
      n += line.split.length
    end
    n
  else
    bytes, chars, lines, words = 0, 0, 0, 0
    File.open(filename) do |f|
      while (line = f.gets)
        lines += 1
        words += line.split.length
        chars += line.chars.length
        bytes += line.bytesize
      end
    end
    [bytes, chars, words, lines]
  end
end