On Wednesday 19 August 2009 01:45:22 pm Josh Cheek wrote:
> My previous version would probably be better like this:
>
> start = Time.now
> puts "Starting to read file ..."
> puts "The number of tokens is: %d." % File.open(ARGV[0]){|f|
> f.inject(0){|a,l| a+l.split.length } } ,
>   "It took #{(Time.now - start) * 1000} ms"

Just for fun, here's a verbose, somewhat less magical version:

start = Time.now
filename = ARGV.first

puts 'Starting to read file...'

count = 0
File.open filename do |file|
  file.each_line do |line|
    count += line.split.length
  end
end

puts "The number of tokens is: #{count}."
duration = Time.now - start
puts "It took #{duration*1000} ms"


That is intended to be somewhat self-documenting, so a bit more verbose than I 
might normally do. It does more or less the same thing, in more or less the 
same way. It also seems to be following roughly the pattern you did in Java, 
and I find it _much_ more readable.

Of course, it's a short (benchmark) example, so it's difficult to show Ruby 
really shining here, unless you want to play golf. But even the readable 
version is also far less verbose than the equivalent Java.