Skip to content

Instantly share code, notes, and snippets.

@pvin
Last active May 6, 2019 01:46
Show Gist options
  • Save pvin/39675ae86560f5eba62909e662bd9976 to your computer and use it in GitHub Desktop.
Save pvin/39675ae86560f5eba62909e662bd9976 to your computer and use it in GitHub Desktop.
inject method in ruby(reference : Eloquent ruby)
class Document
def average_word_length
total = 0.0
words.each { |word| total += word.size }
total / word_count
end
end
#This is the kind of problem that the inject method is tailor-made to solve. Like each , inject takes a block and calls the
#block with each element of the collection. Unlike each , inject passes in two arguments to the block: Along with each
#element, you get the current result—the current sum if you are adding up all of the word lengths. Each time inject calls
#the block, it replaces the current result with the return value of the previous call to the block. When inject runs out of
#elements, it returns the result as its return value. Here, for example, is our average_word_length method, reworked to use
#inject :
def average_word_length
total = words.inject(0.0){ |result, word| word.size + result}
total / word_count
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment