haseeb haseeb - 7 months ago 21
Ruby Question

Purpose of %w in ruby on rails

I see in routes.rb like this

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


And when I see
home
controller , it doesn't have nay actions which list above. But the link works properly.

I want to know what these lines of codes do?

Answer
%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( )

Comments