Create Array of Strings

Download ruby eBook

Example

Arrays of strings can be created using ruby's percent string syntax:

array = %w(one two three four)

This is functionally equivalent to defining the array as:

array = ['one', 'two', 'three', 'four']

Instead of %w() you may use other matching pairs of delimiters: %w{...}, %w[...] or %w<...>.

It is also possible to use arbitrary non-alphanumeric delimiters, such as: %w!...!, %w#...# or %w@...@.

%W can be used instead of %w to incorporate string interpolation. Consider the following:

var = 'hello'

%w(#{var}) # => ["\#{var}"]
%W(#{var}) # => ["hello"]

Multiple words can be interpreted by escaping the space with a \.

%w(Colorado California New\ York) # => ["Colorado", "California", "New York"]

Stats

Contributors: 4
2016-08-29
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook