You can use the Array#join
method to convert an array to a string, separated by the given separator. For example, to separate each string with a comma and a space (i.e. ",
"), you would do the following:
numbers = [1, 2, 3].join(", ") puts numbers #=> "1, 2, 3" puts numbers.class #=> String
If no separator is specified, the default separator for Array#join
is used (as defined by the $,
global variable). If both the separator and $,
are nil
, then an empty string is used as a separator:
numbers = [1, 2, 3].join puts numbers #=> "123" puts numbers.class #=> String
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.