Skip to content

Instantly share code, notes, and snippets.

@jah2488
Created March 20, 2015 05:03
Show Gist options
  • Save jah2488/457496b8995bdd4456fd to your computer and use it in GitHub Desktop.
Save jah2488/457496b8995bdd4456fd to your computer and use it in GitHub Desktop.
I would like this

I like to manipulate data structures. Sometimes the final out put of that manipulation is a string. So I find myself using the pattern of map + join and its starting to feel like the map + flatten of old. Sadly, ruby does not have an answer for this yet, so this is what I've written in the mean time.

def map_join(arr, sep, &block)
 arr.map(&block).join(sep)
end

map_join([1, 2, 3, 4, 5], '-') { |x| x ** 2 } #=> '1-4-9-16-25'

or for those more adventurous types

class Array
 def map_join(sep, &block)
   self.map(&block).join(sep)
 end
end

%w(apple foo bar john).map_join('_', &:upcase) #=> 'APPLE_FOO_BAR_JOHN'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment