Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the %w "thing" in ruby?

Tags:

I'm referring to the %w operator/constructor/whatever you may call it, used like this:

%w{ foo bar baz }
=> ["foo", "bar", "baz"]

I have several questions about it:

  • What is the proper name of that %w "thing"? Operator? Literal? Constructor?
  • Does it matter whether I use {}s instead of []s?
  • Are there any other things like this (for example, one that gives you an array of symbols instead)?
  • Can they be nested (one %w inside another %w, in order to create nested arrays)?
  • Where can I find documentation about it?
like image 371
kikito Avatar asked Mar 29 '11 16:03

kikito


People also ask

What does %w do in 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.

What is %W in Ruby on Rails?

%w[hello billing confirmation] is syntax sugar for ["hello", "billing", "confirmation"] . It tells Ruby to break up the input string into words, based on the whitespace, and to return an array of the words.

What does '?' Mean in Ruby?

i know that the '?' in ruby is something that checks the yes/no fulfillment.

What is %q in Ruby?

Alternate double quotes The %Q operator (notice the case of Q in %Q ) allows you to create a string literal using double-quoting rules, but without using the double quote as a delimiter. It works much the same as the %q operator.


1 Answers

1) It is a litteral, where it is a % then a r(regular expression), w(array), q(string) etc to denote different litterals.

2)

ruby-1.9.2-p136 :001 > %w{1 2 3}
 => ["1", "2", "3"] 
ruby-1.9.2-p136 :002 > %w[1 2 3]
 => ["1", "2", "3"] 

ruby-1.9.2-p136 :008 > %w!a s d f!
 => ["a", "s", "d", "f"] 

ruby-1.9.2-p136 :009 > %w@a s d f@
 => ["a", "s", "d", "f"] 

So you can see that you can use any charater as long as it marks both the beginning and end of the content.

3)

Here are some other examples:

Strings:(%q or %Q)

ruby-1.9.2-p136 :016 > %Q[ruby is cool]
 => "ruby is cool" 
ruby-1.9.2-p136 :017 > %q[ruby is "cool"]
 => "ruby is \"cool\"" 

Regex: (%r)

ruby-1.9.2-p136 :019 > %r[(\w+)]
 => /(\w+)/ 

Sys command: (%x)

ruby-1.9.2-p136 :020 > %x[date]
 => "Tue Mar 29 12:55:30 EDT 2011\n"

4) They cannot be nested because the %w means white space divided array. So if you try to do multi level, it would look like this:

ruby-1.9.2-p136 :003 > %w{1 %w{2 3 4} 5}
 => ["1", "%w{2", "3", "4}", "5"] 

To accomplish this, you would need to use the more verbose syntax:

ruby-1.9.2-p136 :011 > [1, [2,3,4], 5]
 => [1, [2, 3, 4], 5] 
like image 73
Mike Lewis Avatar answered Sep 18 '22 17:09

Mike Lewis