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?
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#charssimply 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 callinjectwhich 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 value1, and on each iteration multiply the value by the integer value of each character.