So, I’ve been training a new employee who has some academic programming experience but no Ruby experience. I decided to revitalize my NubyGems series because now instead of trying to remember what I tripped over almost two years ago, I have active conversations with someone new to the language to work from.

I am going to try to post them unabridged, but try to keep them short and really simple. Whenever my friend asks an interesting question, you’ll see my explanations along with some IRB examples.

People with less than 3 months of Ruby experience, please give me feedback on these as to whether they are helpful. I promise to clarify things in articles or expound a bit more if things are hard to understand.

But for now, the NubyGems experiment continues!


(01:58:52) Dinko: I keep seeing the %w what's that do
(01:59:18) Me: have you installed irb yet?
(01:59:31) Me: >> %w[a b c]
=> ["a", "b", "c"]
(01:59:36) Me: it's just a shortcut
(02:00:33) Me: says, what follows is an array of strings seperated by spaces
(02:01:17) Me: for clarity, note that any symbolic delimiter can be used
(02:01:20) Me: >> %w(a b c)
=> ["a", "b", "c"]
>> %w$a b c$
=> ["a", "b", "c"]
>> %w~a b c~
=> ["a", "b", "c"]
(02:01:35) Me: [] is most common because it's semantically meaningful
(02:01:39) Me: reminds you of arrays
(02:01:50) Me: but () is common because some other languages do it that way
(02:02:28) Me: note also the flexibility that affords
(02:02:30) Me: >> %w~a [ c~
=> ["a", "[", "c"]

Hopefully this little discussion helps shed light on what %w is useful for

Now, you see these all over the place, but one thing I find myself using them over and over for is dynamic requires. I get sick of typing stuff like:

require "foo"
require "bar"
require "baz"

So a lot of times, you’ll see me write stuff like:

%w[ foo bar baz ].each { |lib| require lib }

Now that might make me just a tad bit lazy, but I think that looks pretty! :)