Ruby 初心者的筆記之 Code School – Try Ruby
Ruby 的網站就有教學,第一個是 Code School 提供的 Try Ruby。
筆記
1. 驚嘆號
ticket = [12, 47, 35]
ticket.sort!
驚嘆號 !
表示直接更改物件內容,所以最後 ticket
會是 [12, 35, 47]
,反之沒有驚嘆號就只會回傳新值而不會更改 ticket
。
另一個例子:
poem = "A quick brown dog jumps over the lazy fox. The quick brown fox jumps over a lazy dog."
["dog"] = "cat"
上面的範例,最後 poem
會變成 "A quick brown cat jump over the lazy fox. The quick brown fox jumps over a lazy dog."
,注意到只有第一個 dog
變成 cat
,最後的那個 dog
不變。這裡雖然沒加驚嘆號,但 poem
的內容還是被改了。
所以驚嘆號只適用於 method or action?
Exclamation Points. Methods may have exclamation points in their name, which just means to impact the current data, rather than making a copy. No big deal.
Method 後面加上驚嘆號表示它的行為會影響到原本的資料,而不是傳回一份被更動過的副本。
Square Brackets. With these, you can target and find things. You can even replace them if necessary.
方括號是用來搜索,需要的話找到目標也可以把它取代掉。
Comments