Skip to content

Instantly share code, notes, and snippets.

@foreverman
Created February 18, 2013 08:52
Show Gist options
  • Save foreverman/4976004 to your computer and use it in GitHub Desktop.
Save foreverman/4976004 to your computer and use it in GitHub Desktop.
class Integer
def sum_of_digits
#why the following inject method call works?
#[1,2].inject(0) {|object, *args| object.send('+', *args)}
to_s.split('').map(&:to_i).inject(0, &:+)
end
end
# why the following doesn't work
[12, 34].inject(0, &:sum_of_digits)
# The reason is code above will be converted to something like
[12, 34].inject(0) {|obj, *args| obj.send(:sum_of_digits, *args)}
#this works
[12, 34].inject(0){|sum, n| sum += n.sum_of_digits}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment