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.
- # p003rubystrings.rb
- =begin
- Ruby Strings
- In Ruby, strings are mutable
- =end
- puts "Hello World"
- # Can use " or ' for Strings, but ' is more efficient
- puts 'Hello World'
- # String concatenation
- puts 'I like' + ' Ruby'
- # Escape sequence
- puts 'It\'s my Ruby'
- # New here, displays the string three times
- puts 'Hello' * 3
- # Defining a constant
- # More on Constants later, here
- # /satishtalim/ruby_names.html
- PI = 3.1416
- 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.
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:
- 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:
- 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.
- system("tar xzf test.tgz") # => true