Vishu Kolekar
Vishu Kolekar

Reputation: 51

what is the meaning of "#$e" in ruby 2.1.2

I have one string which is contain char like "Pi#$e77L09!($".

But when i tried to print on Console its prints like "Pi!($"

2.1.2 :002 > str = "Pi#$e77L09!($" => "Pi!($"

2.1.2 :003 > puts str Pi!($ => nil

Upvotes: 3

Views: 157

Answers (2)

sachin bhoi
sachin bhoi

Reputation: 1

try puts 'Pi#$e77L09!($'

'#' is the special character which uses for interpolation of string in ruby.

if you use 'Pi#$e77L09!($' it will add \ String Literals before the '#'

Upvotes: 0

coderhs
coderhs

Reputation: 4837

The magic is in #. As you know "#{ ruby code }" executes the code in the block and prints it. Similarly, # allows you to access global variables of a program by putting a hash in front of it like so "#$a".

so if you try this code.

$a = 'test'
puts "#$a"

you will see that it prints test. So in your case since $e77L09 is a non-existent global variable it prints nothing.

if you want to print that string as a string you will need to print it in single quotes. 'Pi#$e77L09!($'

The above usage of "#$1 #$2" is really useful when you use regex. When a string has multiple matching regex it becomes accessible using $1, $2, $3, etc. This stuff came from the Perl world I believe (I am not 100% sure about its history).

EDIT: Like Global Variable supports class and instance variables can be accessed as well.

Upvotes: 5

Related Questions