Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Aug 17 ’10

Joining elements of an Array to a String

Coming from Java, it’s likely you share my simple “for-each-loop”-fixation:

tags = ["ruby", "rails", "java"]
concatenated_tags = ""
tags.each { |tag| concatenated_tags << "#{tag}, " }
concatenated_tags # => "ruby, rails, java, "
#now, remove the unnecessary comma and space at the end
concatenated_tags.chop!.chop! # => "ruby, rails, java"

Ruby Arrays have a far more sophisticated function to solve the problem. Just use the join method and you’re done:

concatenated_tags = tags.join(', ') # => "ruby, rails, java"

This tip was submitted by Sven Kräuter.

7 notes 0 comments

  1. 5v3n-blog reblogged this from rubyquicktips
  2. 5v3n-blog liked this
  3. atm09td reblogged this from rubyquicktips
  4. 5v3n-blog submitted this to rubyquicktips

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

View the discussion thread.
blog comments powered by Disqus
[フレーム]

AltStyle によって変換されたページ (->オリジナル) /