Live data from Hacker News

(1..100).inject(&:+)

weblog.raganwald.com

1–10 of 66 posts

Re: (1..100).inject(&:+)

#5

Hahaha... Reg, it's like you wrote this in response to the recent article on Monkeypatching floating around here... Thanks! I enjoyed your writing as much as always... and it's especially timely today. ( http://news.ycombinator.com/item?id=123071 if you don't know to which I am referring.)

Weeeel...

The truth is, I wrote the idea behind this a while back using String#to_proc to compare the way Ruby (roll your own) and Python (Guido decides) evolve. But considering I have no Python experience, I never published the post.

Then today, for some reason, I was thinking about Open Classes again :-)

Re: (1..100).inject(&:+)

#7
post #6

Anyone want to explain that code to someone who doesn't know Ruby?

I'm not a ruby programmer and it's not immediately obvious what the result would be.

I know a pretty large number of languages to the point where, unless it's LISP, I can look at code in any language and have some idea of what it does. When a languages gets "so cool" that it's cryptic than I no longer see the benefit.

Re: (1..100).inject(&:+)

#8
post #6

Anyone want to explain that code to someone who doesn't know Ruby?

Sums the first 100 integers. You are basically injecting a function (plus in this case) between each element and evaluating it (to describe in very non-technical sense).

Re: (1..100).inject(&:+)

#9
post #2

Why I hate ruby.

Since I don't use ruby either...I tried a web based interpreter.

   >> (1..100).inject(&:+)                                                 
   TypeError: wrong argument type Symbol (expected Proc)                   
     from (irb):1         
I also am not a fan of doing things a thousand different obscure ways. I like doing things one way, and having that way highly optimized. Typing 10 characters or 20 characters doesn't impact my programming speed, I spend far more time thinking about how to do things the right way.

edit:

Ok, did his monkeypatch and it worked. You get 5050. So it is equiv to sum(range(101)) in python, and much less readable. I fail to see why this is a good thing.

Re: (1..100).inject(&:+)

#10
post #7
post #6

Anyone want to explain that code to someone who doesn't know Ruby?

I'm not a ruby programmer and it's not immediately obvious what the result would be. I know a pretty large number of languages to the point where, unless it's LISP, I can look at code in any language and have some idea of what it does. When a languages gets "so cool" that it's cryptic than I no longer see the benefit.

Would (1..100).fold(&:+) be more obvious? How about (1..100).reduce(&:+)? If either one of those makes sense, perhaps it is a question of Matz choosing Smalltalk's names for methods (collect, select, detect, reject, inject).

Please let me know if changing the name of the method doesn't help.

Post reply on HN