0

I want to take a list of links and split them with alternating joins.

Here's what I have:

ruby-1.9.2-p290 :011 > tmp = [1,2,3,4,5,6].map(&:to_s)
 => ["1", "2", "3", "4", "5", "6"] 
ruby-1.9.2-p290 :012 > tmp2 = []
 => [] 
ruby-1.9.2-p290 :013 > tmp.each_slice(2) {|a| tmp2 << a.join("\t")}
 => nil 
ruby-1.9.2-p290 :014 > tmp2.join("<br\>")
 => "1\t2<br>3\t4<br>5\t6" 

Is there a way to do this in a single line? I know I can do it with a Proc or a block call, but I am hoping for something cleaner. It seems like there is always some Array or Enumerable method I've yet to learn about, but I haven't found anything yet.

4
  • Why do you need map method in :013? Commented Oct 18, 2011 at 23:03
  • Ha, I don't, but I was trying to see if I could get an array out of it... and I didn't clean it out of the code. I'll correct this example. Commented Oct 18, 2011 at 23:08
  • Are you wanting it joined by "<br>", or <br\>"? Commented Oct 18, 2011 at 23:17
  • Oh, hey, good catch. <br\> was the goal. Commented Oct 18, 2011 at 23:26

3 Answers 3

3

You can use map after each_slice, rather than using <<:

[1,2,3,4,5,6].each_slice(2).map {|a| a.join("\t")}.join("<br\>")
Sign up to request clarification or add additional context in comments.

2 Comments

Oh ruby... So beautiful. I was close. Thanks!
You were 30s faster. Didn't see your answer till I posted mine.
2

One liner:

[1,2,3,4,5,6].each_slice(2).map{|d| d.join("\t")}.join("<br/>")

2 Comments

We probably don't need the .map(&:to_s) bit.
@AndrewGrimm Thanks for catching that. :)
0
tmp = [1,2,3,4,5,6].map(&:to_s)
tmp.map { |i| i.to_i % 2 == 1 ? "#{i}\t" : "#{i}<br>" }.to_s

2 Comments

This puts "\t" after 6, which isn't wanted.
Well you did say alternating. Just figured I'd give it a shot. : )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.