![]() | tech note |
| 自分をリファクタリング中。 |
Rubyのシンボルについて、もう一回書いてみる。
前回は完全に他力本願になってしまったので、もう一回書いておく。
irb> "abc" == "abc"
=> true
irb> "abc".equal?("abc")
=> false
irb> :abc == :abc
=> true
irb> :abc.equal?(:abc)
=> true
同じ名前のシンボルは、同じオブジェクトを指しており、「同一」だといえる。irb> "abc".object_id == "abc".object_id
=> false
irb> :abc.object_id == :abc.object_id
=> true
irb> :abc.to_i
=> 16329
irb> 16329.to_sym
=> :abc
数値で管理されているから、生成や比較において文字列よりパフォーマンスがよいわけだ。irb> Symbol.all_symbols.each {|s|
irb> print s, "=", s.to_i, "\\n"
irb> }
irb> hash = {:key => "value"}
=> {:key=>"value"}
irb> hash[:key]
=> "value"
def my_method(x)
puts x[:name]
puts x[:age]
end
my_method({:name => "ruby", :age => 32})
class MyClass
attr_accessor :name
・
・
end
class String
alias :indexOf :index
end
case lang
when :java
...
when :ruby
...
when :vb
...
end