Ruby - User-Defined String Delimiters

Introduction

If single and double quotes aren't convenient for you.

For example, if your strings contain lots of quote characters and you don't want to have to keep putting backslashes.

You can delimit strings in many other ways.

The standard alternative delimiters for double-quoted strings are %Q and / or %/ and /, while for single-quoted strings they are %q and /.

Demo

puts %Q/This is the same as a double-quoted string./ 
puts %/This is also the same as a double-quoted string./ 
puts %q/And this is the same as a single-quoted string/

Result

You can define your own string delimiters.

They must be non-alphanumeric characters.

They may include nonprinting characters such as newlines or tabs.

The delimiters can be various characters that normally have a special meaning in Ruby such as the hash mark (#).

The chosen character should be placed after %q or %Q, and you should be sure to terminate the string with the same character.

If your delimiter is an opening square bracket, the corresponding closing bracket should be used at the end of the string, like this:

Demo

%Q[This is a string]

Here are two examples using an asterisk

  • (*) after %Q instead of a double-quoted string and using an exclamation point
  • (!) after %q instead of a single-quoted string:

Demo

class MyClass 
    attr_accessor :name #   w  w w .ja  va  2s . co  m
    attr_accessor :number 
                         
    def initialize( aName, aNumber ) 
        @name    = aName 
        @number = aNumber 
    end 
    def returnNumber
      return 123
    end                         
end 

ob = MyClass.new( "Java", "007" ) 

puts( %Q*a)Here's a tab\ta new line\na calculation using \* #{2*3} and a method-call #{ob.returnNumber}* ) 
puts( %q!b)Here's a tab\ta new line\na calculation using \* #{2*3} and a method-call #{ob.returnNumber}! )

Result

Related Topic