[Ruby] 2nd round

之前忘了說明一下變數型態,下面是一個我提供的例子:
http://gist.github.com/289506.js?file=gistfile1.rb
可以知道Ruby是一種Dynamically Typed Language(和PHP一樣XD),所以在例中,只是Assign的值不同,但是Ruby卻會有不同的解釋(一個是Fixnum類別,另一個是String類別)

2.1.4.3 Punctuation in identifiers
下面這段是書上對於Variable Scope的範例:
http://gist.github.com/289500.js?file=gistfile1.rb

說實在的那樣寫對我這個白痴來說真的是很難理解,所以我又找到另外一個詳細的解說版本如下:
http://gist.github.com/289510.js?file=gistfile1.rb

是不是清楚許多了呀?最後在這邊再以一個小例子來收個尾:
http://gist.github.com/289511.js?file=gistfile1.rb

你這邊一定會說「媽呀,你根本就沒說到Instance variable和Class variables也想打混過去!!」,好吧,你都這樣說了,那我只好再想些例子來滿足你,先看看定義吧:

A class variable is a variable that is shared amongst all instances of a class. This means that only one variable value exists for all objects instantiated from this class. This means that if one object instance changes the value of the variable, that new value will essentially change for all other object instances.

Instance variables are similar to Class variables except that their values are local to specific instances of an object. For example if a class contains an instance variable called @total, if one instance of the object changes the current value of @total the change is local to only the object that made the change. Other objects of the same class have their own local copies of the variable which are independent of changes made in any other objects.

這邊就簡單的翻譯一下它的意思:

Class Variables(類別變數)就是一種可以在同一個類別下的實體物件間互相分享的一種變數,當有一個實體改變了它的值,另一個實體也會存取到被改變後的值。

而Instance Variables(實體變數)則是個別存在於各實體物件下,各自維護自己的實體變數,而不會互相產生衝突。

我知道大家一定不想看英文,我自己翻得也很爛XD,所以我自己用了一個智障簡報來講解一下,看看就好,別太在意,只是想讓大家笑一下XD

(SlideShare真是難看,用Keynote看才可以看到動畫說,我轉了一個Mov檔在下面!)
P.S.原本要直接Embed在文章裡面,不過Hax4.in有點慢…

大概就是這個意思啦,只是簡單解釋一下,反正之後用Code來說明會比較好了解。

參考:Click Me

Leave a Reply

Your email address will not be published. Required fields are marked *