The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Inject & Me - BFFs

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Amos King

Posts: 78
Nickname: adkron
Registered: Jan, 2007

Amos King is a Web Developer for the US Postal Service and for Ramped Media.
Inject & Me - BFFs Posted: Sep 9, 2008 7:08 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Amos King.
Original Post: Inject & Me - BFFs
Feed Title: DirtyInformation
Feed URL: http://feeds.feedburner.com/Dirtyinformation
Feed Description: Information about Ruby/Rails/JRuby/WebDevelpoment/whatever.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Amos King
Latest Posts From DirtyInformation

Advertisement

I find myself turning to Enumberable#inject more and more. It is such a powerful method, yet I rarely see it used in others' code. Here are a couple of examples of the power of inject.

Adding Facorial to All Integers
class Integer
  def factorial
    raise 'Cannot take a factorial of a negative number' if self < 0
    return 0 if self = 0
    (2..self).inject { |total, element| total * element }
  end
end

Removing Touching Matching Elements in an Array Until No Touching Elements Match( thanks Eric )
class Array
  def remove_touchers
    self.inject([]) { |final, element| final == element ? final[0..-2] : final << element }
  end
end

So, why aren't there more people using this method? Is it just forgotten? Are you using Enumberable#inject? How are you using it?

Read: Inject & Me - BFFs

Topic: Audio, Video, Slides: How to Fail With 100% Test Coverage at raleigh.rb Previous Topic   Next Topic Topic: 10 things you could be doing to your code right now

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use