Jeremy Smith
Jeremy Smith

Reputation: 15079

Why isn't this working for recursively reading from hash?

@hash is a global hash that looks something like:

@hash = {
   "xmlns:xsi"    =>"http://www.w3.org/2001/XMLSchema-instance", 
   "xsi:noNamespaceSchemaLocation"=>"merchandiser.xsd", 
   "header"       =>[{"merchantId"=>["35701"], 
   "merchantName" =>["Lingerie.com"], 
   "createdOn"    =>["2011-09-23/00:33:35"]}], 
   "trailer"      =>[{"numberOfProducts"=>["0"]}]
}

And I would expect this to work if I call the method below like:

def amethod
    hash_value("header", "merchantName") // returns "Lingerie.com"
end

def hash_value *attributes, hash = nil
    hash = @hash unless hash
    att = attributes.delete_at.first
    attributes.empty? ? hash[att].first : hash_value(attributes, hash[att].first)
end

Upvotes: 1

Views: 72

Answers (2)

Wayne Conrad
Wayne Conrad

Reputation: 108099

You can't have a default argument after a splat arg. Instead, require that the attribute list be passed as an array, like so:

def hash_value(attributes, hash = @hash)
  return hash if attributes.empty?
  hash_value(attributes[1..-1], hash[attributes.first].first)
end

p hash_value(["header", "merchantName"])         # => "Lingerie.com"
p hash_value(["trailer", "numberOfProducts"])    # => "0"

Upvotes: 1

jschorr
jschorr

Reputation: 3054

Try this:

def hash_value(*attributes, hash)
    hash = @hash unless hash
    att = attributes.delete_at.first
    attributes.empty? ? hash[att].first : hash_value(attributes, hash[att].first)
end

Upvotes: 0

Related Questions