Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How do I join elements of an array together with a prefix?

Tags:

I have an array like so:

["marblecake", "also", "the", 1337]

I would like to get back a string which contains each element of the array prefixed by some specified string, then joined together by another specified string. For example,

["marblecake", "also", "the", 1337].join_with_prefix("%", "__")

should result in

# => %marblecake__%also__%the__%1337

How might I do this?

like image 614
Kyle Kaitan Avatar asked Apr 29 '09 17:04

Kyle Kaitan


People also ask

How do you combine elements in an array?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

How do I join an array to a string in Ruby?

When you want to concatenate array elements with a string, you can use the array. join() method or * operator for this purpose.

How do I combine array elements into strings?

The arr. join() method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ).


1 Answers

If your array is in a then this one-liner will do it

a.map { |k| "%#{k}" }.join("_")

You could easily put this in a function of your own - even add it to the Array class so that you can call it on an array, like in your example.

Note that the '!' version of map (map!) will modify the array in place - perhaps not your intent.

like image 163
Cody Caughlan Avatar answered Oct 14 '22 17:10

Cody Caughlan