Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros and cons of Ruby's general delimited input? (percent syntax)

Tags:

syntax

ruby

I don't understand why some people use the percentage syntax a lot in ruby.

For instance, I'm reading through the ruby plugin guide and it uses code such as:

%w{ models controllers }.each do |dir|
  path = File.join(File.dirname(__FILE__), 'app', dir)
  $LOAD_PATH << path
  ActiveSupport::Dependencies.load_paths << path
  ActiveSupport::Dependencies.load_once_paths.delete(path)
end

Every time I see something like this, I have to go and look up the percentage syntax reference because I don't remember what %w means.

Is that syntax really preferable to ["models", "controllers"].each ...?

I think in this latter case it's more clear that I've defined an array of strings, but in the former - especially to someone learning ruby - it doesn't seem as clear, at least for me.

If someone can tell me that I'm missing some key point here then please do, as I'm having a hard time understanding why the percent syntax appears to be preferred by the vast majority of ruby programmers.

like image 508
brad Avatar asked Feb 14 '10 05:02

brad


3 Answers

One good use for general delimited input (as %w, %r, etc. are called) to avoid having to escape delimiters. This makes it especially good for literals with embedded delimiters. Contrast the regular expression

  /^\/home\/[^\/]+\/.myprogram\/config$/

with

  %r|^/home/[^/]+/.myprogram/config$|

or the string

  "I thought John's dog was called \"Spot,\" not \"Fido.\""

with

  %Q{I thought John's dog was called "Spot," not "Fido."}

As you read more Ruby, the meaning of general delimited input (%w, %r, &c.), as well as Ruby's other peculiarities and idioms, will become plain.


I believe that is no accident that Ruby often has several ways to do the same thing. Ruby, like Perl, appears to be a postmodern language: Minimalism is not a core values, but merely one of many competing design forces.

like image 59
Wayne Conrad Avatar answered Nov 12 '22 17:11

Wayne Conrad


The %w syntax shaves 3 characters off each item in the list... can't beat that!

alt text

like image 31
JRL Avatar answered Nov 12 '22 18:11

JRL


It's easy to remember: %w{} is for "words", %r{} for regexps, %q{} for "quotes", and so on... It's pretty easy once you build such memory aids.

like image 3
hurikhan77 Avatar answered Nov 12 '22 17:11

hurikhan77