Display the value of a variable in itself

97 views Asked by At

I am doing a quine in Ruby that will display its own code in a new file. I'm trying to do like the following to print the variable itself in the new file:

$var = "Some Code%c$var = %c%s%c % [10,34,$var,34,10]%cSome Code" % [10,34,$var,34,10]

The $var variable is empty in the new file, and this is what I want:

Some Text
$var = "Some Code%c$var = %c%s%c % [10,34,$var,34,10]%cSome Code" % [10,34,$var,34,10]
Some Text

When I launch it, I get this in the new file:

Some Code
$var = "" % [10,$var,10]
Some Code

Help please.

1

There are 1 answers

2
dsojevic On

You need to escape the percent sign (%%) located within the string and also wrap the $var assignment expression in parentheses so it's available for the following interpolation like so:

($var = "Some Code%c($var = %c%s%c) %% [10,34,$var,34,10]%cSome Code") % [10,34,$var,34,10]

This should result in the following:

>> ($var = "Some Code%c($var = %c%s%c) %% [10,34,$var,34,10]%cSome Code") % [10,34,$var,34,10]
=> "Some Code\n($var = \"Some Code%c($var = %c%s%c) %% [10,34,$var,34,10]%cSome Code\") % [10,34,$var,34,10]\nSome Code"