Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word array with whitespace

Tags:

arrays

ruby

I came to love word arrays, but today I face a challenge:

 > a = %w[ faq contact 'about us' legal 'bug reports' ]
 => ["faq", "contact", "'about", "us'", "legal", "'bug", "reports'"] 
 > a = %w[ faq contact "about us" legal 'bug reports' ]
 => ["faq", "contact", "\"about", "us\"", "legal", "'bug", "reports'"] 

How can I have whitespace an element?

like image 421
Marius Butuc Avatar asked Dec 10 '12 21:12

Marius Butuc


People also ask

How do you put a space in an array?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') . Copied!

How to convert array to string with spaces?

To convert an array to a string with spaces, call the join() method on the array, passing it a string containing a space as a parameter - arr. join(' ') . The join method returns a string with all array elements joined by the provided separator. Copied!

How do I print the space between array elements?

For this C code: for(i=0;i<n;i++) printf("%4d",array[i]);

How do you split a space in Javascript?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.


1 Answers

You can escape space characters

a = %w[ faq contact about\ us legal bug\ reports ]
a # => ["faq", "contact", "about us", "legal", "bug reports"]

But I'd still consider using "full" array literals. They are less confusing in this case.

like image 143
Sergio Tulentsev Avatar answered Sep 20 '22 08:09

Sergio Tulentsev