Ruby 2 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.
  1. # p003rubystrings.rb  
  2. =begin  
  3.   Ruby Strings  
  4.   In Ruby, strings are mutable  
  5. =end  
  6.   
  7. puts "Hello World"  
  8. # Can use " or ' for Strings, but ' is more efficient  
  9. puts 'Hello World'  
  10. # String concatenation  
  11. puts 'I like' + ' Ruby'  
  12. # Escape sequence  
  13. puts 'It\'s my Ruby'  
  14. # New here, displays the string three times  
  15. puts 'Hello' * 3  
  16. # Defining a constant  
  17. # More on Constants later, here  
  18. # /satishtalim/ruby_names.html  
  19. PI = 3.1416  
  20. puts PI  
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.
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:
  1. puts `dir`  
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:
  1. puts `ls`  
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.
  1. system("tar xzf test.tgz"# => true