Thursday, June 7, 2012

Care and Grooming of Ruby Symbols - I

Symbols are cool.  But they come with some gotchas of their own.  Bear the following in mind:


(jeremyb@ldn031mac-iMac ~/development/ruby/internal)$irb --version
irb 0.9.5(05/04/13)
(jeremyb@ldn031mac-iMac ~/development/ruby/internal)$irb

>> :yes
=> :yes

>> :yes.to_s
=> "yes"

>> :yes.to_i
=> 18953
>> :yes.eql?("yes")
=> false

>> :yes.equal?("yes")
=> false

>> :yes.to_s.equal?("yes")
=> false

>> :yes.to_s.eql?("yes")
=> true

>> :yes.to_s == ("yes")
=> true

>> a = :yes
=> :yes

>> p a
:yes
=> nil

>> print a
yes=> nil

>> a.to_s
=> "yes"
>> a.to_i
=> 18953

>> a == :yes
=> true

Note too that some applications such as rails and Sinatra may convert symbols to their string values when symbols are passed to controllers.

No comments:

Post a Comment