The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Reducing Code Smell

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
Matt Williams

Posts: 466
Nickname: aetherical
Registered: Feb, 2008

Matt Williams is a jack-of-all trades living in Columbus, OH.
Reducing Code Smell Posted: May 27, 2008 6:27 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Matt Williams.
Original Post: Reducing Code Smell
Feed Title: Ruby Blender
Feed URL: http://feeds2.feedburner.com/RubyBlender
Feed Description: This blog contains short-ish ruby tips, hints, and techniques.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Matt Williams
Latest Posts From Ruby Blender

Advertisement

I had an instance where I'd written some code, using hashes, and knew that there had to be a better way to do it. Performing an inject and adding elements to a hash doesn't work: h[a] = 1 returns the value, not the hash. Here's the smelly code (variables, etc., changed to protect the guilty):

# possibilities is an array
def intersectors(possibilities = [], interceptors = [])
  return { } if possibilities.nil?
  interceptors.inject({ }) do |h, interceptor|
    # returns an array 
    z = foo(interceptor)
    intersect = possibilities & z
    h[interceptor] = intersect unless intersect.empty?
    h
  end
end

So, then I decided to RTFM and found merge. It makes it a lot tighter:

def intersectors(path = [], interceptors = [])
  return { } if path.nil?
  interceptors.inject({ }) do |h, interceptor|
    h.merge(interceptor => x) unless (x=(path & foo(interceptor))).empty?
  end
end

Better, too, I think; I don't have that extraneous h laying around..... I'm also using some syntactic sugar -- ruby is smart enough to make a hash of key/value pairs in a method call, so long as they're the last entities to be passed.

I'm not saying it's baby-fresh, but it certainly stinks less.....

Read: Reducing Code Smell

Topic: Visual Rails, The Sapphire Language and More - The Year So Far Previous Topic   Next Topic Topic: Nginx Logging Format and Awstats

Sponsored Links



Google
  Web Artima.com   

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