0

If I do this:

users.each do |u|
   str += u.id.to_s + ','
end

I will end up with:

1,3,234,234,

Is there a style of looping that won't leave the trailing ',' at the end? I know I can chomp it off after the loop, but was looking for a way to do it w/o having to do that.

2 Answers 2

8

Or even shorter:

users.map(&:id).join ','
2
  • Yeah, I figured that out but wasted time looking up #join before typing. Good catch. Apr 17, 2011 at 1:10
  • @DanneManne Not true at all. There is a practical line between code 'simplicity' and 'readability' that all too often gets tipped in the direction of the former. Not saying you have crossed it with this particular solution, but in regard to your generalized comment I would have to strongly disagree. Given your answer has in fact helped me, I have appropriately upvoted it. Thanks!
    – dooleyo
    May 12, 2013 at 21:34
3
users.map { |u| u.id.to_s }.join ','

And actually, #join will do the #to_s for you, so on second thought:

users.map(&:id).join ','
3
  • can you explain a little what map is doing? &:id is a block?
    – Blankman
    Apr 17, 2011 at 1:15
  • 1
    @Blankman: Look up the documentation for Symbol#to_proc. Basically what it does is equivalent to { |u| u.id }. Apr 17, 2011 at 14:23
  • Right, Ruby should have a FAQ for easily-missed API doc locations. & is always about turning a block into a proc, or, as in this case, a proc into a block. The & operation will try to convert any non-proc argument into a proc with #to_proc. As it happens, if you look up class Symbol in the core API docs, you will find #to_proc, it's shorthand for a block with a single method call. Apr 17, 2011 at 20:14

Your Answer

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

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