ruby 學習筆記(一)

Difference between or and || operator.               

Both or and || return their first argument unless it isfalse, in which case they evaluate and return their second argument. This is shown in the following example:

  1. puts nil || 2008  
  2. puts false || 2008  
  3. puts "ruby" || 2008  

The output is:

  1. >ruby test.rb  
  2. 2008  
  3. 2008  
  4. ruby  
  5. >Exit code: 0  

 

puts 'Hello' * 3  The result is HelloHelloHelloputs `dir`   Just like input dir command=============

     var1 = 5;  

     var2 = '2'  

     puts var1 + var2.to_i 

=============

 

Global scope and global variables

We're starting with the scope that's used least often, but which you need to be aware of: global scope, meaning scope that covers the entire program. Global scope is enjoyed by global variables. Global variables are distinguished by starting with a dollar-sign ($) character. They are available everywhere in your program. Global variables never go out of scope. However, global variables are used very little by experienced programmers (except perhaps a few of the built-in ones).

Built-in global variables

The Ruby interpreter starts up with a fairly large number of global variables already initialized. These variables store information that's of potential use anywhere and everywhere in your program. For example, the global variable$0 contains the name of the file Ruby is executing. The global $: (dollar sign followed by a colon) contains the directories that make up the path Ruby searches when you load an external file.$$ contains the process id of the Ruby process. And there are more.

Local scope

  • The top level (outside of all definition blocks) has its own local scope.
  • Every class or module definition block (class, module) has its own local scope,even nested class/module definition blocks.
  • Every method definition (def) has its own local scope.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章