4

Why would you ever use %w[] considering arrays in Rails are type-agnostic?

user3180
  • 1,369
  • 1
  • 21
  • 38

3 Answers3

10

This is the most efficient way to define array of strings, because you don't have to use quotes and commas.

%w(abc def xyz)

Instead of

['abc', 'def', 'xyz']
jan.zikan
  • 1,308
  • 10
  • 14
7

Duplicate question of

http://stackoverflow.com/questions/1274675/what-does-warray-mean
http://stackoverflow.com/questions/5475830/what-is-the-w-thing-in-ruby

For more details you can follow https://simpleror.wordpress.com/2009/03/15/q-q-w-w-x-r-s/

These are the types of percent strings in ruby:

%w : Array of Strings
%i : Array of Symbols
%q : String
%r : Regular Expression
%s : Symbol
%x : Backtick (capture subshell result)

Let take some example you have some set of characters which perform a paragraph like

Thanks for contributing an answer to Stack Overflow!

so when you try with

%w(Thanks for contributing an answer to Stack Overflow!)

Then you will get the output like

=> ["Thanks", "for", "contributing", "an", "answer", "to", "Stack", "Overflow!"] 

if you will use some sets or words as a separate element in array so you should use \ lets take an example

%w(Thanks for contributing an answer to Stack\ Overflow!)

output would be

=> ["Thanks", "for", "contributing", "an", "answer", "to", "Stack Overflow!"]

Here ruby interpreter split the paragraph from spaces within the input. If you give \ after end of word so it merge next word with the that word and push as an string type element in array.

If can use like below

%w[2 4 5 6]

if you will use

%w("abc" "def")

then output would be

=> ["\"abc\"", "\"def\""]
2

%w(abc def xyz) is a shortcut for ["abc", "def","xyz"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them.

bk chovatiya
  • 343
  • 2
  • 8