RUBY 符號(symbol)

Beck Hsu
Beck Hsu
Nov 1 · 2 min read

符號symbol是什麼

「帶有名字的」一類物件,命名方式如 ‘ :symbol ’

和字串string有什麼不同

符號物件雖是物件,但不能夠改變內容

2.6.3 :004 > :hello[2] = “i”

=>NoMethodError (undefined method `[]=’ for :hello:Symbol)

也有和物件一樣的作法

2.6.3 :001 > :helloworld.length
=> 10

檢查每次映出的物件編號會發現都不一樣,因為在記憶體中都是不同的物件。但符號不同,會有相同的物件編號。

2.6.3 :005 > 5.times do puts “beck”.object_id end
70273860780480
70273856937560
70273856937400
70273856937240
70273856937140
=> 5

2.6.3 :006 > 5.times do puts :beck.object_id end
1525468
1525468
1525468
1525468
1525468
=> 5

字串string和符號的互換方法

符號轉字串

2.6.3 :007 > :book.to_s
=> “book”

字串轉符號

2.6.3 :008 > “book”.to_sym
=> :book

字串物件的使用方法比較多,比如改變字串內容,改變陣列內容,但符號物件不能,所以想要使用較多的功能和方法就用物件字串。

    Beck Hsu

    Written by

    Beck Hsu

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade