Ruby Strings

The word we use for groups of characters is string. Here are some strings:

  • "Hello."
  • "Ruby rocks."
  • "5 is my favorite number... what's yours?"

Some things you can do with strings

irb shell :-

ruby> puts "a\nb\nc"
a
b
c
   nil
ruby> puts 'a\nb\n'
a\nb\nc
   nil
ruby> "\n"
   "\n"
ruby> '\n'
   "\\n"
ruby> "\001"
   "\001"
ruby> '\001'
   "\\001"
ruby> "abcd #{5*3} efg"
   "abcd 15 efg"
ruby> var = " abc "
   " abc "
ruby> "1234#{var}5678"
   "1234 abc 5678"
ruby> "foo" + "bar"
   "foobar"
ruby> "foo" * 2
   "foofoo"

Ruby lets you do several nifty things with strings. Let's create new file with name strings.rb in your project folder.

Here Document in Ruby:

"Here Document" refers to build strings from multiple lines. Following a << you can specify a string or an identifier to terminate the string literal, and all lines following the current line up to the terminator are the value of the string.

If the terminator is quoted, the type of quotes determines the type of the line-oriented string literal. Notice there must be no space between << and the terminator.

print <<EOF
    This is the first way of creating
    here document ie. multiple line string.
EOF


print <<"EOF";                # same as above with difference of quote
    This is the second way of creating
    here document ie. multiple line string.
EOF



print <<`EOC`                 # execute commands as with backtick Remember backtick can execute some system level command we will learn next below
	echo hi there
	echo lo there
EOC



print <<"foo", <<"bar"  # Stacking strings
	I said foo.
foo
	I said bar.
bar

 

Ruby BEGIN Statement

Syntax:

BEGIN {
   code
}

Declares code to be called before the program is run.

puts "This is main Ruby Program"

BEGIN {
   puts "Initializing Ruby Program"
}

Output

Initializing Ruby Program
This is main Ruby Program

Did you notice ? Which line comes first and which comes last ? Check it out and Read again BEGIN code.

Ruby END Statement

Syntax:

END {
   code
}

Declares code to be called at the end of the program.

puts "This is main Ruby Program"

END {
   puts "Terminating Ruby Program"
}

BEGIN {
   puts "Initializing Ruby Program"
}

Output

Initializing Ruby Program
This is main Ruby Program
Terminating Ruby Program

backtick command

It's worth knowing that a special kind of string exists that uses the back-tick (`) or Grave accent as called in the US, as a beginning and ending delimiter. For example:

 
puts `dir`  

#Above command will list all the directory under current linux root.

puts `ls`  

#Aboce command will list all files under same directory.

Loading ...

Related Results :

  1. Ruby Strings
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author