[…]
puts File.readlines(‘some_file.txt’).inject(0) {|total,line| total +
line.split(“\t”)[1].to_i }
(but if the file is large, that could be terribly inefficient)
[…]
Hello,
inject is a method of Iterable, so it’s unnecessary to read the whole
file into memory first to use it. I would prefer a solution that is
both elegant and efficient:
[…]
inject is a method of Iterable, so it’s unnecessary to read the whole
I think you meant Enumerable
Hello,
you’re right, of course. Writing programs in Java and Scheme in
parallel and replying to a Ruby thread in between apparently caused
some mixup of contexts in my head
[…]
– When C++ is your hammer, every problem looks like your thumb.
Maybe “Iterable” is something from C++?
g
I think, the C++ STL has “iterator”, “Iterable” can, for example, be
found in Java…
Just because you can still write your Perl in Ruby, doesn’t mean that
you should.
An example from Matz (Ruby in a Nutshell):
ruby -ne ‘print if /Ruby/’ /usr/share/dict/words
Matz put these features in Ruby so that they could be used,
not so that they would not be used.
But in your blind arrogance, you believe that because of your
very special two-digit IQ, you are the sole arbiter of what is
permissible with Ruby. And when someone dares to post code that
does not conform to your standards of bloat, pretentiousness,
pomposity, inefficiency, and intellectual mediocrity, you lash
out with self-righteous savagery.
As a man and as a programmer, you are a sick joke.
#!/usr/bin/ruby
awk “{t += $2} END {print t}” some_file.txt
Matz put these features in Ruby so that they could be used,
not so that they would not be used.
But in your blind arrogance, you believe that because of your
very special two-digit IQ, you are the sole arbiter of what is
permissible with Ruby. And when someone dares to post code that
does not conform to your standards of bloat, pretentiousness,
pomposity, inefficiency, and intellectual mediocrity, you lash
out with self-righteous savagery.
As a man and as a programmer, you are a sick joke.
Well, I have a two-hexdigit IQ
Note that I don’t fault your awk example, but I stand by my opinion.
If the OP ever responds, we’ll know who’s advice has more long-term
value. My initial response pointed out that the local variable, total,
was scoped within the block and that the split portion of the line
needed to be converted to an arithmetic value before being added to
the total.
I made the assumption that chutsu wanted to learn something about Ruby
and not just how to obtain a very specific result. If there’s more to
his/her situation, your one-liner won’t make it too far.