DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Ruby Array Extension Method To Return Array Elements As Quoted Strings

10.06.2010
| 4921 views |
  • submit to reddit
        // Ruby Array extension method to return array elements as quoted strings

class Array
  def to_quoted_s(q="'")
    "#{q}#{self.join("#{q}, #{q}")}#{q}"
  end
end

Example:

a = ['a', 'b', 'c', 'd', 'e']
puts a.to_s # abcde
puts a.to_quoted_s # 'a', 'b', 'c', 'd', 'e'
puts a.to_quoted_s("\"") # "a", "b", "c", "d", "e"