Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby output contents of an array as a comma separated string Ruby

Is there a more correct way to output the contents of an array as a comma delimited string

@emails = ["[email protected]", "[email protected]", "[email protected]"]  @emails * ","  => "[email protected]", "[email protected]", "[email protected]" 

This works but I am sure there must be a more elegant solution.

like image 468
chell Avatar asked Aug 22 '11 10:08

chell


People also ask

How do I turn an array into a string in Ruby?

In Ruby, we can convert an array into a string using the join method. The join method takes the array and a separator as the arguments. It then separates the elements in the array using the specified separator value.

How do you split an array in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

Can you print an array in Ruby?

Ruby printing array contentsThe array as a parameter to the puts or print method is the simplest way to print the contents of the array. Each element is printed on a separate line. Using the inspect method, the output is more readable. The line prints the string representation of the array to the terminal.

How to break down a string to an array in Ruby?

In addition, Ruby 2.5 introduced the delete_prefix & delete_suffix methods, which may be useful to you. Taking a string & breaking it down into an array of characters is easy with the split method. By default split will use a space as the separator character, but you can pass an argument into this method to specify a different separator.

What is the difference between concat and << in Ruby?

Note: Starting with Ruby 2.4, there is a small difference, with concat you can pass multiple arguments, with << you can pass only one at a time. There is only one problem left. If you want to combine a string with variables, but one of the variables isn't a string, you'll get an unexpected result.

What is a substring in Ruby?

A substring is a smaller part of a string, it’s useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.

How to convert a Ruby object to a string?

Ruby calls the to_s method on the string interpolation block, this tells the object to convert itself into a string.


1 Answers

Have you tried this:

@emails.join(",") 
like image 168
Henrik Avatar answered Sep 22 '22 12:09

Henrik