How does Ruby evaluate double quotes (aka "") and String.new?

What is the difference in how Ruby initializes a new double-quoted string ( "" ) compared to String.new ? For curiosity and experimentation, I tried String#initialize :

 class String def initialize puts "I <3 bananas" # they're delicious! end end 

I am trying to find out why these two examples are different?

 # Calling the String class directly, I can declare banana love! irb(main):054:0> String.new I <3 bananas => "" # Using double quotes, this string is not as tasty :( irb(main):055:0> "" => "" 

This is annoying research because every Google result seems to be oriented towards the basic Ruby syntax, and I could not find anything in the Ruby documentation.

+8
ruby
source share
1 answer

According to Matz :

String objects for literals are already created at compile time, which is far before overriding the initialization method. A single line of objects from literals is only a copy of already selected and initialized objects. The whole purpose of the initialization method is to initialize newly created objects, as the name suggests. I do not feel any need to call the (overridden) initialization method for string literals that were already initialized at compile time.

+9
source share

All Articles