What Is the %W "Thing" in Ruby

What is the %w thing in ruby?

Unsure about the "official" documentation but this is pretty good : http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#The_.25_Notation

Whether you use {} [] () or <> does not matter except if your string contains this character e.g.:

%q{a closing parenthesis: ")"}

The syntax is pretty complex so remembering every variant is not very useful, but it can come in handy when you are hacking quickly and want to avoid taking care of escape characters manually.

What does %w(array) mean?

%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.

Please, explain what %w means

%w creates an array based on the words in it (whitespace separated).

So

%w(the and over)

Will become

["the", "and", "over"]

It is a commonly used method in ruby.

So a portion of your string will be capitalized, unless that portion is either "the", "and" or "over".

Why do you use %w[] in rails?

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']

Purpose of %w in ruby on rails


%w( about mission path standard getting_started welcome infection instruction implementation ).each do |page|
get page, to: "pages##{page}"
end

The code works like: %w(foo bar)is a shortcut for array["foo", "bar"]

.each do |page| 

It loops each element such as in 1st loop the value of page = "foo"

get page, to: "pages##{page}"

This line will become

get foo, to: "pages#foo"

when user hits /foo you will be redirected to foo action of pages controller, this will be same for other elements too.

Thus, this makes easy to define routes for all the elements in %w( )

%w{ models }.each do |dir| in Rails means?

%w{ foo bar baz } creates an array ["foo", "bar", "baz"], it's a shortcut to save typing some quotes and commas. %{ models } just creates an array ["models"], which does seem slightly superfluous, but is probably just for keeping the style consistent (?).

Why favor the use of %w over ['foo', 'bar']

For three reasons:

  1. %w is more idiomatic ruby

When reading ruby code you will come across %w a lot when dealing with an array of strings. While you can write a simple [] and achieve the same thing %w is the 'ruby way'.


  1. %w conveys more meaning than []

The second and I think more important reason is %w conveys a more specific meaning. An array created with %w can only hold strings, it cannot for example hold integers. So the code is showing its intent clearer to the programmer by pointing out that this array will only ever have strings.


  1. The Ruby philosophy: Multiple ways to do one thing.

Ruby has a philosophy (rightly or wrongly) that the language should give the programmer multiple options to do the same thing so they can do what they think is right. So if you disagree with the rule thats ok :) Here is an snippet from an interview with the creator of Ruby Yukihiro Matsumoto

Ruby inherited the Perl philosophy of having more than one way to do the same thing. I inherited that philosophy from Larry Wall, who is my hero actually. I want to make Ruby users free. I want to give them the freedom to choose. People are different. People choose different criteria. But if there is a better way among many alternatives, I want to encourage that way by making it comfortable. So that's what I've tried to do. Maybe Python code is a bit more readable. Everyone can write the same style of Python code, so it can be easier to read, maybe. But the difference from one person to the next is so big, providing only one way is little help even if you're using Python, I think. I'd rather provide many ways if it's possible, but encourage or guide users to choose a better way if it's possible. - Yukihiro Matsumoto 2003 http://www.artima.com/intv/rubyP.html

Ruby Rails %r and %w

A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /.../ and %r{...} literals, and by the Regexp::new constructor.

%r and %w seem to be doing the same thing so I'm confused..

%w{ fred.gif fred.jpg FRED.Jpg}
# => ["fred.gif", "fred.jpg", "FRED.Jpg"]
%r{ a b }
# => / a b /

No. They are not same, as you can see above.

One thing I noticed with %r{}, as you don't need to escape slashes.

# /../ literals:
url.match /http:\/\/example\.com\//
# => #<MatchData "http://example.com/">

# %r{} literals:
url.match %r{http://example\.com/}
# => #<MatchData "http://example.com/">

Use %r only for regular expressions matching more than one '/' character.

# bad
%r(\s+)

# still bad
%r(^/(.*)$)
# should be /^\/(.*)$/

# good
%r(^/blog/2011/(.*)$)

Space in the ruby array by %w

Escape it:

%w(a b\ c) # => ["a", "b c"]

ruby: what does the asterisk in p *1..10 mean

It's the splat operator. You'll often see it used to split an array into parameters to a function.

def my_function(param1, param2, param3)
param1 + param2 + param3
end

my_values = [2, 3, 5]

my_function(*my_values) # returns 10

More commonly it is used to accept an arbitrary number of arguments

def my_other_function(to_add, *other_args)
other_args.map { |arg| arg + to_add }
end

my_other_function(1, 6, 7, 8) # returns [7, 8, 9]

It also works for multiple assignment (although both of these statements will work without the splat):

first, second, third = *my_values
*my_new_array = 7, 11, 13

For your example, these two would be equivalent:

p *1..10
p 1, 2, 3, 4, 5, 6, 7, 8, 9, 10


Related Topics



Leave a reply



Submit