% notation in Ruby

Today I wanna share about the %notation I learned.

Any single non-alpha-numeric character can be used as the delimiter.

1.9.3-p327 :005 > %*lala lala "hehe"*
 => "lala lala \"hehe\""
1.9.3-p327 :006 > %&lala lala "hehe"&
 => "lala lala \"hehe\""

As you can see, * worked, & worked, so other symbol and friends will work too. Above example is using % notation to produce string, but % notation is actually more powerful than that, you can use it to produce array, regexp, shell command:

%Q{one\ntwo\n#{ 1 + 2 }}
=> "one\ntwo\n3"

%q{one\ntwo\n#{ 1 + 2 }}
=> "one\\ntwo\\n#{ 1 + 2 }"

=> /nemo/i

%w{one two three}
=> ["one", "two", "three"]

%i{one two three} # after Ruby 2.0
=> [:one, :two, :three]

%x{ruby --copyright}
=> "ruby - Copyright (C) 1993-2009 Yukihiro Matsumoto\n"

The post is not an exhaustive guide, but an introduction. Here’s where I copied the material from: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#The_.25_Notation

Take a tour to % notation through the link if you haven’t, it is definitely beneficial!

If you’re familiar with test, you can try the examples written in minitest:

It’s from this blog post: http://teohm.github.io/blog/2012/10/15/start-using-ruby-percent-notation/

It’s a tiring day… It’s time to get some rest! Good night 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s