Common Ruby Idioms

Common Ruby Idioms

The magic if clause that lets the same file serve as a library or a script:

if __FILE__ == $0
# this library may be run as a standalone script
end

Packing and unpacking arrays:

# put the first two words in a and b and the rest in arr
a,b,*arr = *%w{a dog was following me, but then he decided to chase bob}
# this holds for method definitions to
def catall(first, *rest)
rest.map { |word| first + word }
end
catall( 'franken', 'stein', 'berry', 'sense' ) #=> [ 'frankenstein', 'frankenberry', 'frankensense' ]

The syntatical sugar for hashes as method arguments

this(:is => :the, :same => :as)
this({:is => :the, :same => :as})

Hash initializers:

# this
animals = Hash.new { [] }
animals[:dogs] << :Scooby
animals[:dogs] << :Scrappy
animals[:dogs] << :DynoMutt
animals[:squirrels] << :Rocket
animals[:squirrels] << :Secret
animals #=> {}
# is not the same as this
animals = Hash.new { |_animals, type| _animals[type] = [] }
animals[:dogs] << :Scooby
animals[:dogs] << :Scrappy
animals[:dogs] << :DynoMutt
animals[:squirrels] << :Rocket
animals[:squirrels] << :Secret
animals #=> {:squirrels=>[:Rocket, :Secret], :dogs=>[:Scooby, :Scrappy, :DynoMutt]}

metaclass syntax

x = Array.new
y = Array.new
class << x
# this acts like a class definition, but only applies to x
def custom_method
:pow
end
end
x.custom_method #=> :pow
y.custom_method # raises NoMethodError

class instance variables

class Ticket
@remaining = 3
def self.new
if @remaining > 0
@remaining -= 1
super
else
"IOU"
end
end
end
Ticket.new #=> Ticket
Ticket.new #=> Ticket
Ticket.new #=> Ticket
Ticket.new #=> "IOU"

Blocks, procs, and lambdas. Live and breathe them.

 # know how to pack them into an object
block = lambda { |e| puts e }
# unpack them for a method
%w{ and then what? }.each(&block)
# create them as needed
%w{ I saw a ghost! }.each { |w| puts w.upcase }
# and from the method side, how to call them
def ok
yield :ok
end
# or pack them into a block to give to someone else
def ok_dokey_ok(&block)
ok(&block)
block[:dokey] # same as block.call(:dokey)
ok(&block)
end
# know where the parentheses go when a method takes arguments and a block.
%w{ a bunch of words }.inject(0) { |size,w| size + 1 } #=> 4
pusher = lambda { |array, word| array.unshift(word) }
%w{ eat more fish }.inject([], &pusher) #=> ['fish', 'more', 'eat' ]

Is there a tutorial that teaches common Ruby programming idioms used by experienced programmers, but may not be obvious to newcomers?

Ruby Idioms (originally from RubyGarden) is my usual reference for idioms. It's clearly organized and fairly complete. As the author says, these are from RubyGarden, which used to be really cool (thanks Wayback Machine). But now seems to be offline.

ruby idioms for using command-line options

A while back I ran across this blog post (by Todd Werth) which presented a rather lengthy skeleton for command-line scripts in Ruby. His skeleton uses a hybrid approach in which the application code is encapsulated in an application class which is instantiated, then executed by calling a "run" method on the application object. This allowed the options to be stored in a class-wide instance variable so that all methods in the application object can access them without exposing them to any other objects that might be used in the script.

I would lean toward using this technique, where the options are contained in one object and use either attr_writers or option parameters on method calls to pass relevant options to any additional objects. This way, any code contained in external classes can be isolated from the options themselves -- no need to worry about the naming of the variables in the main routine from within the thingy class if your options are set with a thingy.verbose=true attr_writer or thingy.process(true) call.

ruby idiom for update or insert a hashmap

Rather then what you did, a better way is:

hashmap = Hash.new{|h, k| h[k] = 0}

Then you only need to do:

hashmap[key] += 1

ruby syntactic sugar: dealing with nils

For the first I'd recommend ick's maybe (equivalent to andand)

"a string".match(/abc(.+)abc/).maybe[1]

I am not sure I understand the second one, you want this?

var = something.very.long.and.tedious.to.write || something.other

What is a programming idiom?

A programming idiom is the usual way to code a task in a specific language. For example a loop is often written like this in C:

for (i=0; i<10; i++)

PHP will understand a similar construct:

for ($i = 1; $i <= 10; $i++)

But it is discouraged in PHP for looping over an array. In this case you would use:

foreach ($arr as $value)

Whereas in Ruby, you would use:

(1..10).each

for the loop, or:

array.each

There are many many possibilities to write a loop in those languages. Using the idiom makes it immediately identifiable by experienced readers. They can then spend their time on more important problems.

Ruby's tap idiom in Python

You can implement it in Python as follows:

def tap(x, f):
f(x)
return x

Usage:

>>> tap([], lambda x: x.append(1))
[1]

However it won't be so much use in Python 2.x as it is in Ruby because lambda functions in Python are quite restrictive. For example you can't inline a call to print because it is a keyword, so you can't use it for inline debugging code. You can do this in Python 3.x although it isn't as clean as the Ruby syntax.

>>> tap(2, lambda x: print(x)) + 3
2
5


Related Topics



Leave a reply



Submit