I often need to do some operations in a loop and some other operations between the iterations. A simple example would be collecting words from an array into a string, spelled backwards and separated with commas. Is there an idiom or language support for this in any language? (For now i am mostly interested in Ruby.)

I usually do something like

a = ['foo', 'bar', 'baz']
s = ''
n = a.size - 1
i = 0
loop do
  s << a[i].reverse
  break if i == n
  s << ', '
  i += 1

But i know no way to save this half iteration if using a ruby iterator:

s = ''
['foo', 'bar', 'baz'].each do |w|
  s << w.reverse
  # ???
  • How about nesting them? – Sean McSomething Feb 26 '13 at 21:21
  • Can you be more specific, please? – Alexey Feb 26 '13 at 21:22
  • If a variant of fold or reduce is unavailable, I'd just initialize s and i with the results of the first iteration instead of "empty" values. Then the condition can be moved onto the loop. – Izkata Feb 27 '13 at 2:12

This is called the loop-and-a-half problem. You've described a popular solution.

People who are into functional programming solve many instances of this with a function that is usually called reduce, which takes a list and performs a binary operation for every element but the first with the result of the previous calculation, and the next value. This function is available in Ruby under both the names inject and reduce. See http://ruby-doc.org/core-2.0/Enumerable.html#method-i-reduce for more.

  • Unfortunately, this solution will not look very clear inside a template language like ERB or Haml, at least i do not see how to make it clear. – Alexey Feb 26 '13 at 22:41
  • In haskell, I believe this is called a fold – Daniel Kaplan Feb 26 '13 at 22:59
  • It seems that this is an inherent fault in all loop constructs that i know: for some reason the default exit point is always put just before the entry point, but i see no reason whatsoever for this to be a common scenario. In my opinion, most loops are "loops-and-a-half". – Alexey Feb 27 '13 at 9:58
  • 1
    @tieTYT Fold is a bit more generalized. In Haskell, it will still append the comma to the first element, because you provided it something to fold into, behind the collection of items being folded. foldl1 on the other hand, uses the first element of the collection as its start point, and will work the same way reduce does in Ruby. – KChaloux Feb 27 '13 at 13:50

This is how you could do it in haskell:

let a = ["foo", "bar", "baz"]  --I've defined my "a" just like you defined it
Data.List.intercalate "," (map reverse a)  --here's the call that does what you want
"oof,rab,zab"  --this is the output

The code in the parenthesis calls the reverse function on every element of "a" (eg: "foo" becomes "oof"). You take the result of that, and in another function you concatenate the elements together with "," in between them.

Here's the key thing to take away here: Sometimes you have functions that change every element and returns another list (eg: map reverses every element, but it still returns a list). Other times you have functions that take a list and returns one element (eg: intercalate will generate one string out of the list of strings you pass in).

These are two separate steps and your code will be easier to reuse if you keep them separate.

I know this isn't answered in ruby, but I'm hoping it's somewhat helpful.


Unfortunately, there is no intercalate like in @tieTYT's answer in ruby. Array#reduce can be used but - e.g. in your example - you have to keep an eye on the order of the elements (reversal of the accumulator memo).
an example in ruby could look like this:

arr = ["foo", "bar", "baz", "goo"]
puts arr.inspect
red = arr.reduce {|memo, item, err|
    "#{memo == arr.first ? memo.reverse : memo}, #{item.reverse}" 
puts red # -> oof, rab, zab, oog

your example - joining the elements of an array together into a string - can easily accomplished with Array#map followed by Array#join (join is like haskell's intercalate, but it does not accept a block in ruby) like:

arr.map{|ele| ele.reverse}.join(", ")

after your comment to @btilly:
IMHO, both look acceptably clear as one-liners in e.g. erb, though the second one is clearly more readable.

<%= arr.reduce{|memo, item| "#{memo == arr.first ? memo.reverse : memo}, #{item.reverse}" } %>
<%= arr.map{|ele| ele.reverse}.join(", ") %>

anyway you can always assign the result to a variable upstream.

  • Hm, it does not look like the output of ERB will be what i want. In fact, i would want to output blocks of HTML in a loop, joining them with other blocks, on so that the ERB or Haml template was easily readable. – Alexey Feb 27 '13 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.