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.
%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.
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.
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.
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}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With