In Ruby, "$,
" is a global variable that's used to specify the default separator to be used for joining elements in the output produced by the Array#join
and Kernel#print
methods.
In the following example, you can see how the output differs for Array#join
with and without setting a value for $,
:
# without setting `$,` puts [1, 2, 3].join #=> "123" # setting `$,` $, = ', ' puts [1, 2, 3].join #=> "1, 2, 3"
The value you set $,
to is only used when you don't specify a separator as an argument to Array#join
. This means that when you explicitly specify a separator via the argument to Array#join
, it supersedes the value $,
is set to:
# without setting `$,` puts [1, 2, 3].join(',') #=> "1,2,3" # setting `$,` $, = ', ' puts [1, 2, 3].join(',') #=> "1,2,3"
Consider, for example, the following as well, where you can see how the output of Kernel#print
is affected when a value for $,
is set:
# without setting `$,` print 1, 2, 3 #=> 123 # setting `$,` $, = ', ' print 1, 2, 3 #=> "1, 2, 3"
The value of $,
defaults to nil
, which means that, in that case, the Array#join
and Kernel#print
methods won't use a separator between elements.
Please note that using global variables is not considered a good practice as they can lead to confusing and hard-to-maintain code. It is generally recommended to use explicit arguments or options rather than relying on global variables.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.