Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Aug 27 ’10

Embracing Functional Programming

Yehuda Katz posted a question on Twitter the other night: what’s the easiest way to get [“X::Y::Z”, “X::Y”, “X”] from “X::Y::Z” in Ruby?
I was determined to accomplish this with a nice application of functional programming. In other words, how can I accomplish this without running procedural code?

The first part is to split the string on ::, which is simple enough with the split command. Next, we obviously need to iterate, but neither ‘each' nor 'map' give access to the other elements. Enter 'inject’.
By seeding inject with an empty array, we can build up the array by using the most recently added element. Behold, the finished product:

module_name = "X::Y::Z"
module_name.split('::').inject([]) { |memo,x| memo.unshift(memo.empty? ? x : "#{memo[0]}::#{x}") }
=> ["X::Y::Z", "X::Y", "X"]

See? No need to use procedural code. Easy to understand with zero side-effects.

Well, you might want to have a look at some old tips and the Ruby API docs:

This tip was submitted by Bradley Grzesiak.

9 notes 0 comments

  1. atm09td reblogged this from rubyquicktips
  2. Bradley Grzesiak submitted this to rubyquicktips


You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus