Tuesday, July 6, 2010

Ruby Strings

It turns out there are several ways to create strings. Here's the ones I know:
  • heredoc
  • String.new
  • String("")
  • String('')
  • using single quotes
  • using double quotes
  • General delimited strings
  • %Q, %q, %x
And now, a bit more on each of these

Heredocs are pretty common across different scripting languages. An example would be this,
a_string = <<HEREDOC
this is some text that
keeps whatever formatting
I give it. Including new lines and tabs
HEREDOC

The last HEREDOC must be on its own line. You can use anything you want. Example:
a_string = <<ANYTHING_YOU_WANT
a string using a heredoc with anything you want

ANYTHING_YOU_WANT

Enough about heredocs.

Next I listed would be the String.new method. All it does is initialize an empty string
str = String.new
puts str
""

str = String; str = ''; str = ""; str = String(''); str = String("")
Same as String.new

A note about single vs double quotes. Single quotes translate the string literally whereas double quotes translate the escaped characters into tabs, newlines, etc.
str = 'a string\nwith a newline character'
puts str
a string\nwith a newline character

str = "a string\nwith a newline character"
puts str
a string
with a newline character

General delimited strings!! These are nice. Those other methods are just.. hm.. but delimited strings, what power!
Demonstration:
str = %^this is a string^
puts str
this is a string

You can use whatever delimiter (nearly) you want to use.
%Q acts the same as double quotes and %q acts the same as single quotes.
%x acts just like backticks, ``. That means you can wrap system commands in %x instead of using backticks :)

You can always checkout strings from ruby-doc.org

Bye

No comments:

Post a Comment