Fun with Strings
String literals are sequences of characters between single or double quotation marks.
'' (ie. two single quotes) does not have anything in it at all; we call that an empty string.
Here's a program p003rubystrings.rb that explores strings to some extent:
a. If puts is passed an
object that is not a string, puts calls the
to_s method of that object and prints the
string returned by that method.
b. In Ruby, strings are mutable. They
can expand as needed, without using much time and memory. Ruby
stores a string as a sequence of characters.
c. Introduced in Ruby 2.3, the magic string of #
frozen_string_literal: true
will freeze literal
strings, allowing specific strings to be mutable by prepending
a +
directly before the opening string delimiter.
Using .dup
on a string will allow the cloned
string to be mutable as well, allowing for benefits from
mutating strings, when that makes sense to do so.
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:
The command output string is sent to the operating system as a command to be executed (under windows operating system, we have sent the dir command), whereupon the output of the command (dir on a command window would display all the files and sub directories in your folder) is then displayed by puts.
On Linux and Mac, you can instead do:
Another way to spawn a separate process is to use the Kernel method system. The method executes the given command in a sub-process; it returns true if the command was found and executed properly. It returns false if command exited with a nonzero exit status, and nil if the command failed to execute. Remember, the command's output will simply go to the same destination as your program's output.
Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on rubylearning.github.io and in the course at rubylearning.org is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.