Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $/ mean in Ruby?

I was reading about Ruby serialization (http://www.skorks.com/2010/04/serializing-and-deserializing-objects-with-ruby/) and came across the following code. What does $/ mean? I assume $ refers to an object?

 array = []
 $/="\n\n"
 File.open("/home/alan/tmp/blah.yaml", "r").each do |object|
   array << YAML::load(object)
 end
like image 435
Peter Black Avatar asked May 20 '16 13:05

Peter Black


4 Answers

$/ is a pre-defined variable. It's used as the input record separator, and has a default value of "\n".

Functions like gets uses $/ to determine how to separate the input. For example:

$/="\n\n"
str = gets
puts str

So you have to enter ENTER twice to end the input for str.

Reference: Pre-defined variables

like image 90
Yu Hao Avatar answered Nov 15 '22 10:11

Yu Hao


This code is trying to read each object into an array element, so you need to tell it where one ends and the next begins. The line $/="\n\n" is setting what ruby uses to to break apart your file into.

$/ is known as the "input record separator" and is the value used to split up your file when you are reading it in. By default this value is set to new line, so when you read in a file, each line will be put into an array. What setting this value, you are telling ruby that one new line is not the end of a break, instead use the string given.

For example, if I have a comma separated file, I can write $/="," then if I do something like your code on a file like this:

foo, bar, magic, space

I would create an array directly, without having to split again:

["foo", " bar", " magic", " space"]

So your line will look for two newline characters, and split on each group of two instead of on every newline. You will only get two newline characters following each other when one line is empty. So this line tells Ruby, when reading files, break on empty lines instead of every line.

like image 35
Tormyst Avatar answered Nov 15 '22 10:11

Tormyst


I found in this page something probably interesting: http://www.zenspider.com/Languages/Ruby/QuickRef.html#18

$/ # The input record separator (eg #gets). Defaults to newline.

like image 40
GondraKkal Avatar answered Nov 15 '22 12:11

GondraKkal


The $ means it is a global variable.

This one is however special as it is used by Ruby. Ruby uses that variable as a input record separator

For a full list with the special global variables see: http://www.rubyist.net/~slagell/ruby/globalvars.html

like image 39
Oscar Klein Heerenbrink Avatar answered Nov 15 '22 11:11

Oscar Klein Heerenbrink