Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: what's the difference between initializing a string using quotes vs colon?

Tags:

ruby

Whats' the difference between initializing a string using quotes vs preceding it with the colon? I.e "bobo" vs :bobo. When you inspect them they appear the same but when you compare them the result evaluates to false.

irb(main):006:0> r = "bobo"
=> "bobo"
irb(main):007:0> puts r
bobo
=> nil
irb(main):008:0> t = :bobo
=> :bobo
irb(main):009:0> puts t
bobo
=> nil
irb(main):010:0> puts r == t
false
=> nil
irb(main):011:0> s = "bobo"
=> "bobo"
irb(main):012:0> puts r == s
true
=> nil
like image 739
Ya. Avatar asked Nov 30 '22 12:11

Ya.


1 Answers

"bobo" is a string whereas :bobo is a symbol.

:bobo.class # => Symbol
"bobo".class # => String

String#==

If obj is not a String, returns false. Otherwise, returns true if str <=> obj returns zero.

So according to the documentation "bobo" == :bobo # => false and "bobo" == "bobo" # => true. - This is expected.

puts :bobo 
# >> bobo
:bobo.to_s # => "bobo"

This is because puts applying to_s on the Symbol object :bobo. See Symbol#to_s

like image 117
Arup Rakshit Avatar answered Dec 24 '22 16:12

Arup Rakshit