Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby %w(...) vs %w[...]

Tags:

ruby

Is there a difference between %w(don matt james) and %w[don matt james] in Ruby?

Using the Ruby Console, both of them output an array with each word as an element. I'm curious why there are multiple ways to do this - and how each way is supposed to be used.

like image 486
Don P Avatar asked Nov 03 '13 22:11

Don P


People also ask

What is %w Ruby?

%w(foo bar) is a shortcut for ["foo", "bar"] . Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.

How do you check if an array contains a value Ruby?

To check if a value is in the array, you can use the built-in include? method. The include? method returns true if the specified value is in the array and false if not.

Are strings arrays in Ruby?

With a Ruby string array, we can store many strings together. We often prefer iterators, not loops, to access an array's individual elements. In Ruby programs, we use string arrays in many places.


2 Answers

Either option is fine, and produces the same result. There are even a couple of additional variations on the syntax:

%w'don matt james'
%w{don matt james}
like image 189
Peter Goldstein Avatar answered Nov 09 '22 23:11

Peter Goldstein


There is no difference. Any single non-alpha-numeric character or any "paired" set of characters can be used as delimiters, as covered in http://en.wikibooks.org/w/index.php?title=Ruby_Programming/Syntax/Literals (see "The % Notation") and http://www.ruby-doc.org/core-2.0.0/doc/syntax/literals_rdoc.html#label-Percent+Strings

like image 22
Peter Alfvin Avatar answered Nov 10 '22 01:11

Peter Alfvin