Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do string literals in ruby bypass new/initialize, and is there a way to instrument this?

Tags:

ruby

internals

I was playing with an idea this afternoon, and stumbled into something I don't quite understand. Basically what I'm trying to achieve in this experiment is to somehow know every time a string is created (for later use, such as in some kind of DSL). The following works fine for any String that is created via String.new:

class ::String
  class << self
    alias_method :new_orig, :new
    def new(*args)
      o = new_orig(*args)
      puts "newing '#{o}'"
      o
    end
  end
  alias_method :initialize_orig, :initialize
  def initialize(*args)
    initialize_orig(*args)
    puts "initializing '#{self}'"
  end
end

e.g.

irb > String.new("foo")
initializing 'foo'
newing 'foo'
 => "foo"

What I can't figure out is how a String object is created when you use a literal. For example, why does this not go through the same initialization and setup:

irb > "literal string"
 => "literal string"

I realize that the compiler is doing something or other differently when a string is literal, but doesn't it need to be initialized, simply to be a fully functional object? Are there any tricks that I could use to determine when a string is created using a literal, or is that impossible to do?

Thanks!

like image 959
Mason Cloud Avatar asked Oct 29 '12 19:10

Mason Cloud


1 Answers

I think that from the discussion it follows, that hardly anyone here will give you genuine answer, unless Chris Heald wakes up and actually looks at that source code as he promised. But if, as you say in your comment to your question, the purpose is 'testing the boundaries of what the language can do to have some fun and learn something new', then let me introduce you - as much as I hate SlideShare - to this Ruby presentation by famous esoteric programmer Yusuke Endoh.

like image 155
Boris Stitnicky Avatar answered Sep 28 '22 02:09

Boris Stitnicky