Ruby/Language Basics/Symbols
Материал из Wiki.crossplatform.ru
Содержание[убрать] |
id2name
#!/usr/bin/env ruby name = "myValue" name.to_sym # => ":myValue" :myValue.id2name # => "myValue" name == :myValue.id2name # => true
object_id of three string with the same value
"name".object_id # => -605973716 "name".object_id # => -605976356 "name".object_id # => -605978996
object_id of three symbols with the same name
:name.object_id # => 878862 :name.object_id # => 878862 "name".intern.object_id # => 878862 "name".intern.object_id # => 878862
Ruby uses tons of symbols internally. To prove it, execute this line of Ruby code
Symbol.all_symbols
Symbol in an array
myArray = ["January", 1, :year, [2006,01,01]] myArray.each {|e| print e.class, " " } # => String Fixnum Symbol Array
symbols is placeholders for identifiers and strings.
# You can recognize symbols because they are always prefixed by a colon (:). # You don"t directly create a symbol by assigning a value to it. # You create a symbol by calling the to_sym or intern methods on a string or by assigning a symbol to a symbol. name = "myValue" name.to_sym # => :myValue :myValue.id2name # => "myValue" name == :myValue.id2name # => true
Using Symbols as Hash Keys
people = Hash.new people[:nickname] = "M" people[:language] = "J" people["last name".intern] = "M" p people[:nickname] p people["nickname".intern]