天天看點

Ruby變量Ruby變量

Ruby變量

2010-07-09 星期五 小雨 ruby與大部分腳本語言不同,它有自己的命名規則(采用CoC): 1. 常量(Constants) :首字母必須大寫(一般是整個單詞都是大寫的) A variable whose name begins with an uppercase letter (A-Z) is a constant. A constant can be reassigned a value after its initialization, but doing so will generate a warning. Every class is a constant.(因為/是以在ruby中,類名都是首字母大寫的) Trying to substitute the value of a constant or trying to access an uninitialized constant raises the NameError exception.

例子:FOOBAR 2. 局部變量(Local Variables) 與強類型語言(如C、C++、Java一樣): A variable whose name begins with a lowercase letter (a-z) or underscore (_) is a local variable or method invocation. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block's opening brace to its close brace {}. A local variable is only accessible from within the block of its initialization. For example:

i0 = 1
loop {
  i1 = 2
  puts defined?(i0)	# true; "i0" was initialized in the ascendant block
  puts defined?(i1)	# true; "i1" was initialized in this block
  break
}
puts defined?(i0)	# true; "i0 was initialized in this block
puts defined?(i1)	# false; "i1" was initialized in the loop      

與腳本語言不同(如perl),不需要前面加$符号,也不需要my關鍵詞。 3. 執行個體變量(Instance Variables) A variable whose name begins with '@' is an instance variable of self. An instance variable belongs to the object itself. Uninitialized instance variables have a value of nil. 例如:@foobar

#!/usr/bin/ruby

class Customer
   def initialize(id, name, addr)
      @cust_id=id
      @cust_name=name
      @cust_addr=addr
   end
   def display_details()
      puts "Customer id #@cust_id"
      puts "Customer name #@cust_name"
      puts "Customer address #@cust_addr"
    end
end

# Create Objects
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

# Call Methods
cust1.display_details()
cust2.display_details()      

4. 類變量(Class Variables) A class variable is shared by all instances of a class. 其實就是類靜态變量 例子: @@foobar

#!/usr/bin/ruby

class Customer
   @@no_of_customers=0
   def initialize(id, name, addr)
      @cust_id=id
      @cust_name=name
      @cust_addr=addr
   end
   def display_details()
      puts "Customer id #@cust_id"
      puts "Customer name #@cust_name"
      puts "Customer address #@cust_addr"
    end
    def total_no_of_customers()
       @@no_of_customers += 1
       puts "Total number of customers: #@@no_of_customers"
    end
end

# Create Objects
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

# Call Methods
cust1.total_no_of_customers()
cust2.total_no_of_customers()
      

Here @@no_of_customers is a class variable. This will produce following result:

Total number of customers: 1
Total number of customers: 2      

5. 全局變量(Global Variables) A variable whose name begins with '$' has a global scope; meaning it can be accessed from anywhere within the program during runtime. 例子:$foobar

6. 僞變量(Pseudo Variables)

self

Execution context of the current method.

nil

The sole-instance of the 

NilClass

 class. Expresses nothing.

true

The sole-instance of the 

TrueClass

 class. Expresses true.

false

The sole-instance of the 

FalseClass

 class. Expresses false. ( nil also is considered to be  false, and every other value is considered to be  true in Ruby.)

The value of a pseudo variable cannot be changed. Substitution to a pseudo variable causes an exception to be raised.

7. 預定義變量(Pre-defined Variables)

$!         The exception information message set by the last 'raise' (last exception thrown).
[email protected]         Array of the backtrace of the last exception thrown.
      
$&         The string matched by the last successful pattern match in this scope.
$`         The string to the left  of the last successful match.
$'         The string to the right of the last successful match.
$+         The last bracket matched by the last successful match.
$1 to $9   The Nth group of the last successful regexp match.
$~         The information about the last match in the current scope.
      
$=         The flag for case insensitive, nil by default (deprecated).
$/         The input record separator, newline by default.
$/         The output record separator for the print and IO#write. Default is nil.
$,         The output field separator for the print and Array#join.
$;         The default separator for String#split.
      
$.         The current input line number of the last file that was read.
$<         The virtual concatenation file of the files given on command line.
$>         The default output for print, printf. $stdout by default.
$_         The last input line of string by gets or readline.
      
$0         Contains the name of the script being executed. May be assignable.
$*         Command line arguments given for the script.  Same as ARGV.
$$         The process number of the Ruby running this script.  Same as Process.pid.
$?         The status of the last executed child process.
$:         Load path for scripts and binary modules by load or require.
      
$"         The array contains the module names loaded by require.
$LOADED_FEATURES An english friendlier alias to $"
$DEBUG     The status of the -d switch.  Assignable.
$FILENAME  Current input file from $<. Same as $<.filename.
$KCODE     Character encoding of the source code.
$LOAD_PATH An alias to $:
$stderr    The current standard error output.
$stdin     The current standard input.
$stdout    The current standard output.
$VERBOSE   The verbose flag, which is set by the -v switch.
$-0        The alias to $/
$-a        True if option -a ("autosplit" mode) is set. Read-only variable.
$-d        The alias to $DEBUG.
$-F        The alias to $;
$-i        If in-place-edit mode is set, this variable holds the extension, otherwise nil.
$-I        The alias to $:
$-K        The alias to $KCODE.
$-l        True if option -l is set ("line-ending processing" is on). Read-only variable.
$-p        True if option -p is set ("loop" mode is on). Read-only variable.
$-v        The alias to $VERBOSE.
$-w        True if option -w is set.
      

This infestation of cryptic two-character $? expressions is a thing that people will frequently complain about, dismissing Ruby as just another perl-ish line-noise language. Keep this chart handy. Note, a lot of these are useful when working with regexp code.

Note that there are some pre-defined constants at parse time, as well, namely

__FILE__ (current file)
      

and

__LINE__ (current line)      

補充:ruby類型

Ruby Arrays:

Literals of Ruby Array are created by placing a comma-separated series of object references between square brackets. A trailing comma is ignored.

Example:

#!/usr/bin/ruby

ary = [  "fred", 10, 3.14, "This is a string", "last element", ]
ary.each do |i|
   puts i
end      

Ruby Hashes:

A literal Ruby Hash is created by placing a list of key/value pairs between braces, with either a comma or the sequence => between the key and the value. A trailing comma is ignored.

Example:

#!/usr/bin/ruby

hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }
hsh.each do |key, value|
   print key, " is ", value, "/n"
end      

參考資料: 1. Ruby Programming/Syntax/Variables and Constants[ http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Variables_and_Constants] 2. Ruby Variables, Constants and Literals [ http://www.tutorialspoint.com/ruby/ruby_variables.htm]