Hash Referencing

class Hash
  def method_missing(method_id, *args, &block)
    method_name = method_id.to_s
    check = self.stringify_keys
    if check.keys.include?(method_name)
      check[method_name]
    else
      super
    end
  end
end

 

具体示例:

 

    hash = {"project" =>
        {"prototype_url" => nil,
        "designer_id" => 2,
        "finished_at" => nil, "phone_number" => "512225555",
        "website" => "http://www.ggg.com",
        "first_name" => "test",
      }
    }
    p hash.project
    # => {"prototype_url"=>nil, "phone_number"=>"512225555", "finished_at"=>nil, "designer_id"=>2, "website"=>"http://www.ggg.com", "first_name"=>"test"}
    p hash.project.prototype_url # => nil
    p hash.project.designer_id   # => 2
    p hash.project.first_name    # => "test"

 

你可能感兴趣的:(prototype)