Using Ruby Inject
As I mentioned in my last post, I’m running through the problems in Project Euler to learn Ruby. It’s a really fun way of learning a new language while solving interesting problems.
While searching for some help on one of the question I managed to stumble across a very interesting post by Jay Fields that outlines the usage of the Enumerable#inject in Ruby. I’m not going to explain what inject is or how it works – since he does that better than I could – but I am going to show you some scary-looking code that uses inject. (The code isn’t scary, just that one line)
The code below is an attempted answer to Question 10 on Project Euler – Find the sum of all the primes below two million. (It turns out my solution is too slow – I had to think of a different algorithm) The interesting line is highlighted. This is probably the most boring usage of inject you could possibly imagine, but I was still pretty happy that I managed to use it (hey, it’s my first time ok).
Happy coding.