ruby 字串學習筆記3

c3tc3tc3t發表於2015-11-30

ascii轉字元或者字串轉ascii

 

"a".ord # =>  97
"!".ord  # => 33
"\n".ord # => 10

 

'a'[0] # => "a"
'bad sound'[1]  # => "a"

'a'[0].ord # => 97
'bad sound'[1].ord  # => 97
97.chr  # => "a"

 

符號轉字串

:a_symbol.to_s # => "a_symbol"
:AnotherSymbol.id2name  # => "AnotherSymbol"
:"Yet another symbol!".to_s # => "Yet another symbol!"

通過字串得到相應的符號

:dodecahedron.object_id # => 516488
symbol_name = "dodecahedron"
symbol_name.intern # => :dodecahedron
symbol_name.intern.object_id # => 516488

 

符號由一個名字和一個internal id 組成,相同符號引用同一個物件,但是兩個內容一樣的字串卻是不同的物件

"string".object_id   # =>70309575257960
"string".object_id   # =>70309575257221
:symbol.object_id  # => 87690
:symbol.object_id  # => 87690

如果物件內容重要使用字串,如果物件唯一性重要使用符號

相關文章