2014年10月27日 星期一

[ 文章收集 ] RB Learning - Fun with Strings

Source From Here
Preface
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
  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. # http://rubylearning.com/satishtalim/ruby_names.html    
  19. PI = 3.1416    
  20. puts PI   
Notes.
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.

Fun with Strings
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.
  1. system("tar xzf test.tgz") # => true    


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...