<?xml version="1.0" encoding="UTF-8"?>
<post>
  <body>Reposted from an old RubyGarden article

&lt;hr /&gt;

Ruby supports idiomatic programming. Please put your favorite Ruby idioms here. They don't have to be specific to Ruby.

Using idioms does not always lead to the most readable code, but they can provide convenient shortcuts in many situations.

&lt;h2&gt;I want this value, unless it evaluates to false in which case I want another value instead&lt;/h2&gt;

Normally you would write something like

&lt;pre&gt;
  if myvar
    return myvar
  else
    return another_value
  end
&lt;/pre&gt;

But you can use the &lt;code&gt;||&lt;/code&gt; operator instead:

&lt;pre&gt;return myvar || another_value&lt;/pre&gt;

You can also use the &lt;code&gt;||=&lt;/code&gt; operator to assign a value to a variable if it evaluates to false. That is, instead of writing

&lt;pre&gt;myvar = another_value unless myvar&lt;/pre&gt;

or

&lt;pre&gt;
  unless myvar
    myvar = another_value
  end

&lt;/pre&gt;

you could write

&lt;pre&gt;myvar ||= another_value&lt;/pre&gt;

handy to put anything or anthing else, if it doesn't exist(I didn't know about that possibility for a long time):

&lt;pre&gt;puts page_title || "Untitled"&lt;/pre&gt;

&lt;h2&gt;I want this value, unless it is nil in which case I want another value instead&lt;/h2&gt;

Please note the difference between this idiom and the idiom above. In order to clearly see the different behavior assume myvar is &lt;code&gt;false&lt;/code&gt;

&lt;pre&gt;
   myvar.nil? ? other : myvar
&lt;/pre&gt;

And setting myvar if it is nil (again not if it is false )

&lt;pre&gt;
   myvar = newvalue if myvar.nil?
&lt;/pre&gt;

while

&lt;pre&gt;  myvar ||= newvalue&lt;/pre&gt;

corresponds to

&lt;pre&gt;
  myvar = newvalue unless myvar
&lt;/pre&gt;

&lt;h2&gt;Invoke this method on my object, unless I have no object&lt;/h2&gt;

If you want to invoke a method on an object in a variable, but in some cases the variable could be &lt;code&gt;nil&lt;/code&gt;, you could do this:

&lt;pre&gt;
  if myvar
    return myvar.size
  else
    return nil
  end
&lt;/pre&gt;

But using the &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; operator you can turn this into:

&lt;pre&gt;
  return myvar &amp;amp;&amp;amp; myvar.size
&lt;/pre&gt;
If you want to return something other than &lt;code&gt;nil&lt;/code&gt; if both &lt;code&gt;myvar&lt;/code&gt; and &lt;code&gt;myvar.size&lt;/code&gt; are &lt;code&gt;nil&lt;/code&gt;, you can use the &lt;code&gt;||&lt;/code&gt; operator again:

&lt;pre&gt;
  return myvar &amp;amp;&amp;amp; myvar.size &lt;code&gt;||&lt;/code&gt; 0
&lt;/pre&gt;
... or use the ternary operator:
&lt;pre&gt;
  return myvar ? myvar.size : 0
&lt;/pre&gt;

&lt;h2&gt;Run this code only when the file is the main program&lt;/h2&gt;

Sometimes it is useful to add code to a file that is executed only if the file is run as the main program, but is ignored otherwise.  Here's how:
&lt;pre&gt;
  if $PROGRAM_NAME == __FILE__
      do_stuff
  end
&lt;/pre&gt;

Some applications of this idiom:
&lt;ul&gt;
&lt;li&gt; Include test code at the bottom of a library file, so that running the file as a program tests the file.&lt;/li&gt;
&lt;li&gt; Require a program's file into a test module, so that its functions can be tested without running the whole program.&lt;/li&gt;
&lt;li&gt; Provide a Ruby API to a program's functionality.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Destroy this object when it goes out of scope&lt;/h2&gt;

C++ programmers are used to using the "construction acquires, destruction releases" idiom to control the management of external resources such as files or sockets.  They are often put off by Ruby because garbage collection and finalizers don't act like objects on the stack with destructors.

Ruby's blocks can be used to the same end.  In the class that represents an external resource, define a class method that takes a block.  That method

&lt;ul&gt;
&lt;li&gt; allocates an instance of the class, thereby acquiring the resource
&lt;li&gt; passes the instance to the block, and then
&lt;li&gt; releases the resource when the block returns.
&lt;/ul&gt;

Here's an abstract example of this idiom in use:

&lt;pre&gt;
 Resource.open( identifier ) do |resource|
     process( resource )
 end
 # resource is now closed
&lt;/pre&gt;

The implementation of the class method must use a &lt;code&gt;begin...ensure&lt;/code&gt; statement to ensure that the resource is always released:

&lt;pre&gt;
 def Resource.open( identifier )  # :yield: resource
     resource = Resource.new( identifier )
     yield resource
 ensure
     resource.close
 end
&lt;/pre&gt;

A practical example is the &lt;code&gt;open&lt;/code&gt; method of the &lt;code&gt;File&lt;/code&gt; class.

Often, though, the behaviour of new is conditional, depending on whether a block is provided.  For instance, &lt;code&gt;File.open&lt;/code&gt; behaves just like &lt;code&gt;File.new&lt;/code&gt; &lt;em&gt;unless&lt;/em&gt; you provide a block.  This way, programmers can choose between the interfaces.  Applying that to our general &lt;code&gt;Resource&lt;/code&gt; class, we get this:

&lt;pre&gt;
 def Resource.open( identifier )  # :yield: resource
     resource = Resource.new( identifier )
     if block_given?
         begin
             yield resource
         ensure
             resource.close
         end
     else
         return resource
     end
 end
&lt;/pre&gt;
Thus:
&lt;pre&gt;
 r = Resource.open( x )             # -&amp;gt; some Resource object

 Resource.open( x ) do |r|
   # use 'r' ...
 end
&lt;/pre&gt;

&lt;h2&gt;Hashes of lists&lt;/h2&gt;

Sometimes, I want to fill out a hash with keys mapped to lists of arbitrary elements. Instead of the cumbersome approach:

&lt;pre&gt;
    h[key] = [] unless h.has_key? key
    h[key] &amp;lt;&amp;lt; val
&lt;/pre&gt;
which requires three key lookups, you can turn it into
&lt;pre&gt;
    ary = (h[key] &lt;code&gt;||&lt;/code&gt;= [])
    ary &amp;lt;&amp;lt; val
&lt;/pre&gt;
or the even shorter, but less readable:

&lt;pre&gt;
    (h[key] &lt;code&gt;||&lt;/code&gt;= []) &amp;lt;&amp;lt; val
&lt;/pre&gt;

This code still takes two lookups, as &lt;code&gt;h[key] ||= []&lt;/code&gt; is equivalent to &lt;code&gt;h[key] = h[key] || []&lt;/code&gt;. An alternative is:
&lt;pre&gt;
    a = h.fetch(key) { h[key] = [] }
    a &amp;lt;&amp;lt; val
&lt;/pre&gt;

This involves one lookup in the common case, and two lookups when creating the sub-list.

You could also consider using the following:
&lt;pre&gt;
    h = Hash.new []
    h[key] &amp;lt;&amp;lt;= val
&lt;/pre&gt;
but note that this doesn't quite work:
&lt;pre&gt;
    irb(main):001:0&amp;gt; h = Hash.new []
    {}
    irb(main):002:0&amp;gt; h[1] &amp;lt;&amp;lt;= 2; h[2] &amp;lt;&amp;lt;= 3
    [2, 3]
    irb(main):003:0&amp;gt; h
    {1=&amp;gt;[2, 3], 2=&amp;gt;[2, 3]}
&lt;/pre&gt;

Only one array is ever created; we want a new array for every key.  So instead we write:

&lt;pre&gt;
    h = Hash.new { [] }
    h[key] &amp;lt;&amp;lt;= val
&lt;/pre&gt;

You can also use this form:

&lt;pre&gt;
    h = Hash.new{ |h,v| h[v]=[] }
    h[key] &amp;lt;&amp;lt; val
&lt;/pre&gt;

&lt;h2&gt;Jump to first non-false expression&lt;/h2&gt;

Blame Hal Fulton for this (see &lt;a href="http://www.google.com/url?sa=D&amp;q=HTTP%3A%2F%2Fwww.ruby-talk.org%2F58095"&gt;[ruby-talk:58095]&lt;/a&gt;).  His toy language at grad school included a &lt;tt&gt;test&lt;/tt&gt; statement.  It's similar enough to the &lt;tt&gt;case&lt;/tt&gt; statement that ...

For example:
&lt;pre&gt;
   case true
   when x &amp;lt; 0;             puts "x &amp;lt; 0"
   when 0 &amp;lt;= x &amp;amp;&amp;amp; x &amp;lt; 1;   puts "x in interval [0,1)"
   when 1 &amp;lt;= x &amp;amp;&amp;amp; x &amp;lt; 2;   puts "x in interval [1,2)"
   when 2 &amp;lt;= x;            puts "x &amp;gt;= 2"
   end
&lt;/pre&gt;

In fact, you can even omit the "true" and have the same semantics:

&lt;pre&gt;
   case
   when x &amp;lt; 0;             puts "x &amp;lt; 0"
   when 0 &amp;lt;= x &amp;amp;&amp;amp; x &amp;lt; 1;   puts "x in interval [0,1)"
   when 1 &amp;lt;= x &amp;amp;&amp;amp; x &amp;lt; 2;   puts "x in interval [1,2)"
   when 2 &amp;lt;= x;            puts "x &amp;gt;= 2"
   end
&lt;/pre&gt;
Further, you can take advantage of Ruby's functional nature:
&lt;pre&gt;
   puts case
   when x &amp;lt; 0;            "x &amp;lt; 0"
   when 0 &amp;lt;= x &amp;amp;&amp;amp; x &amp;lt; 1;  "x in interval [0,1)"
   when 1 &amp;lt;= x &amp;amp;&amp;amp; x &amp;lt; 2;  "x in interval [1,2)"
   when 2 &amp;lt;= x;           "x &amp;gt;= 2"
   end
&lt;/pre&gt;

&lt;h2&gt;easy to access elements in array&lt;/h2&gt;

&lt;pre&gt;
   val = [1, 2, 3]
   a, b, c = val      # Observe this particular line
   p a    #=&amp;gt; 1
   p b    #=&amp;gt; 2
   p c    #=&amp;gt; 3
&lt;/pre&gt;

This can be useful when you want a method to return multiple values.

&lt;pre&gt;
   def test
      [42, "ruby"]
   end
   val, str = test
&lt;/pre&gt;
Or, if you want just the second value:
&lt;pre&gt;
   val = test[1]
&lt;/pre&gt;&lt;h2&gt;from my_hash['foo'] to my_hash.foo&lt;/h2&gt;
&lt;p&gt;
&lt;p&gt;
If you want to reference a value corresponding to a key in hashes you may use a &lt;em&gt;dotted&lt;/em&gt; notation by several means (take a look at &lt;a href="http://www.google.com/url?sa=D&amp;q=HTTP%3A%2F%2Fblade.nagaokaut.ac.jp%2Fcgi-bin%2Fscat.rb%2Fruby%2Fruby-talk%2F92897"&gt;[ruby-talk:92897]&lt;/a&gt; too).

&lt;p&gt;
&lt;ul&gt;
&lt;li&gt; Hash could be extended to act like a Struct
&lt;/ul&gt;&lt;p&gt;
&lt;pre&gt;
   class Hash
     def method_missing(meth,*args)
       if /=$/=~(meth=meth.id2name) then
         self[meth[0...-1]] = (args.length&amp;lt;2 ? args[0] : args)
       else
         self[meth]
       end
     end
   end
   x = { 'name'=&amp;gt;'Gavin', 'age'=&amp;gt;31 }
   x.weight = 171
   x.feet = ['left','right']
   puts x.name , x.weight , x.foo , x.inspect
   #=&amp;gt;Gavin
   #=&amp;gt;171
   #=&amp;gt;nil
   #=&amp;gt;{"name"=&amp;gt;"Gavin", "weight"=&amp;gt;171, "feet"=&amp;gt;["left", "right"], "age"=&amp;gt;31}

&lt;/pre&gt;&lt;p&gt;
&lt;ul&gt;
&lt;li&gt; You may get a Struct from a Hash using &lt;a href="HTTP://rubyforge.org/snippet/detail.php?type=snippet&amp;amp;id=1"&gt;[Dan Berger's code snippet on RubyForge]&lt;/a&gt; &lt;i&gt;Is this worthwhile, given that &lt;a href="http://rubygarden.org/Ruby/page/show/OpenStruct" class="wikipagelink"&gt;OpenStruct&lt;/a&gt; is in the standard library?&lt;/i&gt;
&lt;/ul&gt;&lt;p&gt;
&lt;pre&gt;
   class Hash
      def to_struct(struct_name)
         Struct.new(struct_name,*keys).new(*values)
      end
   end
   h = {:name=&amp;gt;"Dan"}
   s = h.to_struct("Foo")
   puts "name: " + s.name
&lt;/pre&gt;&lt;p&gt;

&lt;p&gt;
&lt;ul&gt;
&lt;li&gt; &lt;a href="http://rubygarden.org/Ruby/page/show/OpenStruct" class="wikipagelink"&gt;OpenStruct&lt;/a&gt; merges Hash and Struct behaviours together.  It is like a hash, but it uses the &lt;code&gt;obj.key&lt;/code&gt; notation.
&lt;/ul&gt;&lt;p&gt;
&lt;pre&gt;
   require 'ostruct'
   x = OpenStruct.new('name' =&amp;gt; 'Gavin', 'age' =&amp;gt; 31)
   x.weight = 171
   x.feet = ['left', 'right']

   puts x.name       # -&amp;gt; "Gavin"
   puts x.weight     # -&amp;gt; 171
   puts x.foo        # -&amp;gt; nil
   puts x.feet       # -&amp;gt; ['left', 'right']

&lt;/pre&gt;
&lt;h2&gt;Automagical Variable Instantiation with a Hash&lt;/h2&gt;

If you create a hash with a default value, you can get automagical instantiation for that type.  For instance:
&lt;p&gt;
&lt;pre&gt;
  mlock = Hash.new {|h,k| h[k] = Mutex.new }
&lt;/pre&gt;&lt;p&gt;
then later on throughout my code when I need a mutex I say
&lt;p&gt;
&lt;pre&gt;
  mlock["entry"].synchronize do
    # blah
  end
&lt;/pre&gt;&lt;p&gt;

and then later on when I need another I use
&lt;p&gt;
&lt;pre&gt;
  mlock["exit"].synchronize do
    # exit blah
  end
&lt;/pre&gt;
This prevents me from needing to declare a new mutex in &lt;code&gt;initialize&lt;/code&gt; every time I need another mutex in that class.

-- &lt;a href="http://rubygarden.org/Ruby/page/show/CharlesComstock" class="wikipagelink"&gt;CharlesComstock&lt;/a&gt;

&lt;h2&gt;Simulating Java's synchronized keyword&lt;/h2&gt;

First thing we do, is add the synchronized method to object:
&lt;pre&gt;class Object
  def synchronized(obj)
     @_class_locker ||= Hash.new {|h,k| h[k] = Mutex.new }
     @_class_locker[obj.id].synchronize { yield }
  end
end&lt;/pre&gt;

Once we have this, we can use synchronized(variable_name), just like you can in java!
&lt;p&gt;
Example:
&lt;pre&gt;require 'thread'

mytest = "hello world"

thread1 = Thread.new do
  # java like syntax
  synchronized(mytest) {
    puts "1: mytest: #{mytest}"
    sleep 1
    mytest = 'goodbye world'
  }
end

thread2 = Thread.new do
  # ruby syntax
  synchronized mytest do
    puts "2: mytest: #{mytest}"
  end  
end

thread1.join
thread2.join&lt;/pre&gt;
&lt;p&gt;
Results in:
&lt;pre&gt;1: mytest: hello world
2: mytest: goodbye world
&lt;/pre&gt;
&lt;p&gt;
&lt;hr noshade class="wikiline" size="1"&gt;
&lt;p&gt;

Or, for a more ruby'ish example that does not leave any dependencies on the Object class:
&lt;p&gt;
&lt;pre&gt;require 'thread'
module JavaEmulation
  def synchronized(on)
     @_class_locker ||= Hash.new {|h,k| h[k] = Mutex.new }
     @_class_locker[on.id].synchronize { yield }
  end
end

class MyClass
  include JavaEmulation
  def start_threads
    mytest = "hello world"

    thread1 = Thread.new do
      synchronized(mytest) {
        puts "1: mytest: #{mytest}"
        sleep 1
        mytest = 'goodbye world'
      }
    end

    thread2 = Thread.new do
      synchronized mytest do
        puts "2: mytest: #{mytest}"
      end  
    end

    thread1.join
    thread2.join
  end
end

MyClass.new.start_threads&lt;/pre&gt;
&lt;h2&gt;Initializing complex objects&lt;/h2&gt;
&lt;p&gt;
&lt;p&gt;
If an object has a lot of data that needs to be provided on initialization, the traditional method call arrangement is unsuitable, because you need to remember the order of arguments, and you can't omit arguments that you don't care about.  Ruby offers some relief with variable argument lists (&lt;code&gt;def foo(x, y, *args)&lt;/code&gt;) and default values (&lt;code&gt;def foo(x, y=5, *args)&lt;/code&gt;, but for seriously complicated objects, these are typically not enough.
&lt;p&gt;
Passing a hash is one option, using keys of the hash to name the attributes you wish to set.  This allows arbitrary ordering, and selective omission (to allow default values).  See &lt;a href="http://rubygarden.org/Ruby/page/show/KeywordArguments" class="wikipagelink"&gt;KeywordArguments&lt;/a&gt; for a look at this technique.

&lt;p&gt;
But I prefer the following:
&lt;pre&gt;
  complex_object = ComplexObject.new do |c|
    c.width = 15
    c.height = 20
    c.colour = :red
    c.position = [12, 4]
  end
&lt;/pre&gt;
&lt;p&gt;
The benefits:
&lt;ul&gt;
&lt;li&gt; it's easy to code for (see below)
&lt;li&gt; the syntax is arguably more natural than the hash approach (it's very Rubyesque)
&lt;li&gt; it's self-documenting; you can look at the documentation for the &lt;code&gt;ComplexObject&lt;/code&gt; class to see which attributes you can set

&lt;/ul&gt;&lt;p&gt;
The disadvantages:
&lt;ul&gt;
&lt;li&gt; all attributes used must be public
&lt;/ul&gt;-Hey, just create a Struct to be passed to the block. Then this disadvantage disappears.
&lt;p&gt;
The implementation:
&lt;p&gt;
&lt;pre&gt;
  class ComplexObject
    attr_accessor :colour, :position, :width, :height, :depth, :label

      #
      # Width and height _must_ be specified; all others are optional.
      #
    def initialize  # :yield: c
        # Set default values.
      @colour = :white
      @position = [0,0]
      @depth = 0
      @label = ""
      yield self
        # If all attributes are optional, we would code:
        #   yield self if block_given?
      if @width.nil? or @height.nil?
        raise TypeError, "Incompletely specified ComplexObject"
      end
    end
  end
&lt;/pre&gt;
&lt;p&gt;
This, to me, is a very natural coding style.  The default values are easily seen in the code (usually browsable via RDoc).  The post-condition is easily specified.  All in eight clear lines of code for a class with six attributes.
&lt;p&gt;
Morover, this style is extremely useful when creating hierarchies of composite objects. 
i.e.: FXRuby implements this idiom to support well structured GUI code.

&lt;pre&gt;
FXMainWindow.new($app, ...){|mainwindow|
   FXHorizontalFrame.new(mainwindow){|hf|
      FXLabel.new(hf){|label| ... }
      FXButton.new(hf){|button| .. }
   }
}
&lt;/pre&gt;
As you can see, the hierarchic composition of the GUI is reflected by the structure of the code which increases readability and maintainability. I use this idiom whenever I need to build complex composite objects. --henon
&lt;h2&gt;Initializer alternatives&lt;/h2&gt;
&lt;p&gt;
&lt;p&gt;
Ruby allows only one initializer method for a class, which is a problem if you want initialization to be done in different ways, or with different arguments.
&lt;p&gt;
One of the dynamic invocation features of Ruby can be used to relieve this, by writing a class in the following idiom:
&lt;p&gt;
&lt;pre&gt;
  class Example

    def initialize( method_name, *parameters_array )
      send(method_name, parameters_array)
    end

  private
    def initialize1( parameters_array )
      # construct in one way
    end

    def initialize2( parameters_array )
      # construct in another way
    end

  end
&lt;/pre&gt;
&lt;p&gt;

where the arguments are collected into an array, and a name string is used to delegate to a particular method.
&lt;p&gt;
Such a class can then be instantiated variously by the client like this:
&lt;p&gt;
&lt;pre&gt;
  e1 = Example.new( 'initialize1', 1, 2, 3 )
  e2 = Example.new( 'initialize2', 'a', 'b' )
&lt;/pre&gt;
&lt;p&gt;
which practically gives overloaded initializer methods.
&lt;p&gt;
(Ideally, it would be preferable to be able to instantiate like this:
&lt;p&gt;
&lt;pre&gt;
  e = Example.new_alternative1( 1, 2, 3 )
&lt;/pre&gt;

&lt;p&gt;
There is a hack for that:
&lt;p&gt;
&lt;pre&gt;
  class Example

    def initialize( method_name, *parameters_array )
      send(method_name, parameters_array)
    end

    def self.new_alternative1(*parameters_array)
      return Example.new('initialize1', parameters_array)
    end

  private
    def initialize1( parameters_array )
      # construct in one way
    end

    def initialize2( parameters_array )
      # construct in another way
    end

  end
&lt;/pre&gt;
&lt;p&gt;
It would work better through a mixin that metaclass-hacks to allow for easily flagging a method "initializer", though.)
&lt;h2&gt;Wonder of the When-be-splat&lt;/h2&gt;
&lt;p&gt;
On &lt;a href="http://www.google.com/url?sa=D&amp;q=http%3A%2F%2Fredhanded.hobix.com%2Fbits%2FwonderOfTheWhenBeFlat.html"&gt;[redhanded]&lt;/a&gt;  _Why pointed out that * (the splat) can be used to unpack an array for a branch of a case statement.
&lt;p&gt;

&lt;pre&gt;
  BOARD_MEMBERS = ['Jan', 'Julie', 'Archie', 'Stewick']
  HISTORIANS = ['Braith', 'Dewey', 'Eduardo']
&lt;/pre&gt;&lt;p&gt;
&lt;pre&gt;
  case name
  when *BOARD_MEMBERS
   "You're on the board!  A congratulations is in order." 
  when *HISTORIANS
   "You are busy chronicling every deft play." 
  end
&lt;/pre&gt;
</body>
  <created-at type="datetime">2009-11-07T01:07:06Z</created-at>
  <id type="integer">244</id>
  <title>Repost from (long-gone) RubyGarden: List of Ruby Idioms</title>
  <updated-at type="datetime">2009-11-07T01:07:06Z</updated-at>
</post>
