October19

User defined delimiters in Ruby

I came across some ways of specifying different methods for everyday things and how to specify your own delimiters in some of these:

Different ways to enclose a multi-line string

data<<-EOF
 Some multiline
 text here
EOF

data = " 
 Some multiline
 text here
" 

%q{
 Some multiline
 text here
}

# With %q you can specify any operator to act as a delimiter
%q| some text |
%q+ some text +

There are a few variations on the %q theme:

  • %q is equivalent to a string with single quotes
  • %Q is equivalent to a string with double quotes
  • %x is equivalent to using the backticks

Another similar function is:

  • %w{apple computers are sexy} – which produces a string array of the words provided e.g. [“apple”,”computers”,”are”,”sexy”] – you can use your own delimiters in the same way as %q above.

Posted by kingsleyh | Filed in Ruby |

Sorry, comments are closed for this article.