0

I am new to Ruby. Can someone help me understand what does following statement do?

%w(www us ca jp)
Kuldeep Yadav
  • 1,664
  • 5
  • 23
  • 41
  • 2
    Search for "The % Notation" [here](https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals). `%w(www us ca jp) #=> ["www", "us", "ca", "jp"]` is simply a shorthand way of constructing an array of strings. `%w| www us ca jp |`, `%w[ www us ca jp ]`, `%w{ www us ca jp}`, `%w%www us ca jp%`, etc. return the same array of strings. Similarly, `%i` is used to produce an array of symbols. For example, `%i{one two three} #=> [:one, :two, :three]`. – Cary Swoveland Apr 26 '23 at 08:04
  • Notice also that `%w! Mary\ had a little\ lamb ! #=> ["Mary had", "a", "little lamb"]`. – Cary Swoveland Apr 26 '23 at 15:47
  • You need to remove the ruby-on-rails tag as this is a pure-Ruby question. – Cary Swoveland Apr 26 '23 at 16:48
  • My guess is that you got the downvote based on the fact, that the question does not show your research effort, and that you did not show any context as to where this Ruby expression occurs. Basically, you are talking about a Ruby _statement_ and show a Ruby _expression_. – user1934428 Apr 27 '23 at 06:34

1 Answers1

4

That is a String-Array Literal.

Quote from the docs:

%w and %W: String-Array Literals

You can write an array of strings with %w (non-interpolable) or %W (interpolable):

%w[foo bar baz]       # => ["foo", "bar", "baz"]
%w[1 % *]             # => ["1", "%", "*"]
# Use backslash to embed spaces in the strings.
%w[foo\ bar baz\ bat] # => ["foo bar", "baz bat"]
%w(#{1 + 1})          # => ["\#{1", "+", "1}"]
%W(#{1 + 1})          # => ["2"]
spickermann
  • 100,941
  • 9
  • 101
  • 131