## 2014年10月14日 星期二

### [ Ruby Gossip ] Basic : 變數、操作與物件 - 變數

Source From Here
Preface

>> x = 1.0
=> 1.0
>> y = x
=> 1.0
>> x.object_id
=> 3696828
>> y.object_id
=> 3696828 # y 與 x 指向同一個物件, 故 object_id 相同
>> y = 2.0
=> 2.0
>> x.object_id
=> 3696828
>> y.object_id
=> 20871252 # 此時 y 指向不同物件

>> x = 1
=> 1
>> x.object_id
=> 3
>> x = x + 1
=> 2
>> x.object_id
=> 5 # 此時 x 指向新的物件, 故 object_id: 3->5

>> x = [1, 2]
=> [1, 2]
>> x.object_id
=> 2042
>> x[0]=10
=> 10
>> x
=> [10, 2]
>> x.object_id
=> 2042 # 因為 x 指向 array, 即使 array 內容變動, 只要 x 指向同一個 array, object_id 就不變.

>> list1 = [1, 2, 3]
=> [1, 2, 3]
>> list2 = [1, 2, 3]
=> [1, 2, 3]
>> list1 == list2 # == 用來比對 array 內容是否相同
=> true
>> list1.object_id
=> 21564936
>> list2.object_id
=> 21538056
>> list1.equal? list2 # .equals? 比對是否相同物件
=> false

>> x = 1.0
=> 1.0
>> y = 1
=> 1
>> x == y
=> true
>> x.eql? y
=> false
>> x.eql? 1.0
=> true

Ruby 區域變數有個特性，直譯器只要看到程式碼中有「變數=值」的語句，就會為建立該變數，這會造成有以下的結果:

- main.rb
1. \$x = 10
2. x = 20
3. puts "%d, %d" % [\$x, x]
4.
6.
7. puts "%d, %d" % [\$x, x]
- util.rb
1. \$x = 100
2. x = 200

# ruby main.rb
10, 20
100, 20

>> \$\$
=> 4656
>> require "English"
=> true
>> \$PID
=> 4656

\$\$ 可以取得目前程式的行程 ID，要求 English 特性之後，可以用較清楚的名稱使用全域變數，例如 \$PID 就等於 \$\$。

>> XCONST = 10
=> 10
>> XCONST = 20
(irb):2: warning: already initialized constant XCONST
=> 20

### [ Python 文章收集 ] List Comprehensions and Generator Expressions

Source From  Here   Preface   Do you know the difference between the following syntax?  view plain copy to clipboard print ? [x  for ...