The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Undenting Strings

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Andrew Johnson

Posts: 39
Nickname: jandrew
Registered: Mar, 2004

Simple things ...
Undenting Strings Posted: Mar 26, 2004 12:40 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Andrew Johnson.
Original Post: Undenting Strings
Feed Title: Simple things ...
Feed URL: http://www.siaris.net/index.cgi/index.rss
Feed Description: On programming, problem solving, and communication.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Andrew Johnson
Latest Posts From Simple things ...

Advertisement
byline: Andrew L Johnson

One extremely nice feature about Ruby is that here-doc terminators may be indented (if the terminator specification begins with a hyphen). This means it is not necessary to either put here-docs at the left margin, or to quote some hardcoded amount of whitespace in the terminator specification (as in Perl). Here-docs can make nice easy templates for simple code generation — but what about whitespace sensitivity of the generated code (such as RDoc markup)?

The following is a simple regex to strip common leading spaces from a multi-line string (added as a method to the String class in this example):

  class String
    def undent
      a = $1 if match(/\A(\s+)(.*\n)(?:\1.*\n)*\z/)
      gsub(/^#{a}/,'')
    end
    alias :dedent :undent
  end

And now, if you have some method that returns a here-doc, you can simply dedent it:

  class SomeTemplate
    def some_meth(foo,bar)
      <<-STOP.dedent
        * #{foo} list item
          * sublist with #{bar} item
      STOP
    end
  end

  x = SomeTemplate.new
  puts x.some_meth('first', 'second')
  __END__

  output:

  * first list item
    * sublist with second item

Not rocket science, but I find it handy to have a dedent method lying around for just such uses.

Read: Undenting Strings

Topic: An a2ps syntax file for Ruby Previous Topic   Next Topic Topic: Operator Overloading Stupidity


Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2017 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us