 
 This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.
| Making a Hash More Like a Struct | ||
|---|---|---|
| Code | Expected | Actual | 
| require 'rubygems'
require 'facet/hash/to_ostruct'
cliches = { 'hammer' => 'tongs', :lock => ['stock', 'barrel'] }
cliches_struct = cliches.to_ostruct
cliches_struct.hammer | "tongs" | "tongs" | 
| cliches_struct.lock | ["stock", "barrel"] | ["stock", "barrel"] | 
| cliches_struct.rolling_stone | nil | nil | 
| class StructlikeHash < Hash
  def method_missing(name, *args)
    if include?(name)
      self[name]
    elsif include?(name.to_s)
      self[name.to_s]
    else
      super
    end
  end
end
cliches = StructlikeHash['cat' => 'mouse', 'grin' => { 'bear' => 'it' } ]
cliches.cat | "mouse" | "mouse" | 
| cliches.creek | NoMethodError: undefined method `creek' for {"cat"=>"mouse", "grin"=>{"bear"=>"it"}}:StructlikeHash
... | NoMethodError: undefined method `creek' for {"cat"=>"mouse", "grin"=>{"bear"=>"it"}}:StructlikeHash
	from (irb):15:in `method_missing'
	from (irb):21
 | 
| class StructlikeHash2 < Hash
  def method_missing(name, *args)
    if include?(name)
      self[name]
    elsif include?(name.to_s)
      self[name.to_s]
    else
      begin
        super
      rescue NoMethodError 
        nil
      end
    end
  end
end
cliches = StructlikeHash2['cat' => 'mouse', 'grin' => { 'bear' => 'it' } ]
cliches.creek | nil | nil | 
| cliches[:keys] = 'to the kingdom' cliches[1] = 'and only' cliches[:top] = 'of the world' cliches["top"] = 'to bottom' cliches.keys | ["cat", :top, 1, "grin", "top", :keys] | ["cat", :top, 1, "grin", "top", :keys] | 
| cliches.top | "of the world" | "of the world" | 
| cliches.1 | SyntaxError: compile error ... | SyntaxError: compile error
(irb):45: no .<digit> floating literal anymore; put 0 before dot
cliches.1
        ^
(irb):45: parse error, unexpected tINTEGER
cliches.1
         ^
	from (irb):45
 |