Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 476
popedotninja Avatar asked Apr 22 '13 03:04

popedotninja


People also ask

What is the main difference between single quotes and double quotes Ruby?

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.

What's the difference between single quotes or double quotes when using string interpolation?

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.

How do you add a double quote to a string in Ruby?

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.


1 Answers

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.

like image 94
Darshan Rivka Whittle Avatar answered Sep 27 '22 21:09

Darshan Rivka Whittle