views:

29

answers:

3

I've been learning ruby by solving project euler problems and in one solution to a problem I saw you could do something like "12341".chars.inject(1) { |prod, n| prod * n.to_i }.

I've looked on the ruby doc but I can't find where String#chars is defined.

Can anyone explain how that works?

+1  A: 

It is documented here.

Shadwell
+1  A: 

It isn't present in 1.8.6, which is what you get if you look at http://ruby-doc.org/core/, but it's present in the 1.8.7 and 1.9 documentation.

String#chars simply returns an Enumerator (a class that provides the Enumerable interface) which yields each of the characters of the string in turn. This allows you to call inject which will iterate over each of the items in the Enumerable, applying a block to that item and a value in which you collect results. In this case, you start with the value 1, and on each iteration multiply the value by the integer value of each character.

Brian Campbell
It is listed in the 1.8.7 documentation: http://ruby-doc.org/core-1.8.7/classes/String.html#M000777
sepp2k
Ah, you're right. A simple Google search got me to http://ruby-doc.org/core/classes/String.html which turns out to be the 1.8.6 documentation; I hadn't checked the 1.8.7 docs.
Brian Campbell
Ahhh, that's where I was going wrong. I didn't realize there were 1.8.7 docs.
kertap
A: 

Rails' ActiveSupport had originally monkeypatched String#chars as well. Were they using Rails or ActiveSupport in the answer?

Andrew Grimm
They weren't. It was regular ruby. But I think this monkey patching is something I need to look into some more.
kertap