What's the difference in how Ruby initializes a new string with double quotes (""
) vs. String.new
? For curiosity and experimentation purposes, I overrode String#initialize
:
class String
def initialize
puts "I <3 bananas" # they're delicious!
end
end
What I'm trying to figure out is: why are these two examples 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 to research because every Google result seems to be focused on basic Ruby syntax, and I haven't been able to find anything in the Ruby documentation.
The basic difference between these two methods is Single quotes can not hold/print escape sequences directly, while double quotes can. i.e. Double quoted strings are used for String Interpolation in Ruby.
The essential difference between the two literal forms of strings (single or double quotes) is that double quotes allow for escape sequences while single quotes do not! A string literal created by single quotes does not support string interpollation and does not escape sequences.
Single-quoted and double-quoted strings are (almost) equivalent in Ruby. Of course, you have to escape \' inside single-quoted strings and \" inside double-quoted strings.
According to Matz:
String objects for literals are already created in the compile time, which is far before you redefine the initialize method. The individual string objects from literals are just copy of the already allocated and initialized objects. The whole purpose of the initialize method is to initialize newly created objects, as the name suggests. I don't feel any need to call the (redefined) initialize method for string literals, that already initialized at the compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With