开发者

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

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.


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.


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

alt text


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.


As the size of the array grows, the %w syntax saves more and more keystrokes by not making you type in all the quotes and commas. At least that's the reason given in Learning Ruby.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜