Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trace string creation in Ruby?

Tags:

ruby

trace

In this answer to a separate question, I said that if you do

name = "Rohit " "Sharma"

you don't create two String objects with the contents "Rohit " and "Sharma" that combine to create a new String object with the contents "Rohit Sharma", but that you only create a single String object to start off with.

But it's only a book telling me that, rather than manually verifying it.

How would you be able to log the creation of a String?

I tried using

set_trace_func proc { |event, file, line, id, binding, classname|
  printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
}

string = "Insert content here"

But only got

c-return -:3  set_trace_func   Kernel
    line -:5

And "Programming Ruby 1.9" (the Pickaxe) says that modifying Class#new wouldn't work for strings, as they're constructed without using new.

like image 473
Andrew Grimm Avatar asked Apr 01 '26 02:04

Andrew Grimm


1 Answers

You can't log this, since this concatenation doesn't happen at runtime. It happens at parse time.

In other words: regardless of whatever code you write to log this, the concatenation will have happened long before your code ever gets run.

In yet other words: you trust that there's only one string object created the same way that you trust that 42 only creates one Fixnum object with the value 42, not 42 Fixnum objects with the value 1: the ISO Ruby Language Specification says so, and the source code of every single existing Ruby implementation says so, and every Ruby book ever written says so.

like image 105
Jörg W Mittag Avatar answered Apr 02 '26 20:04

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!