开发者

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

@hash is a global hash that looks something like:开发者_如何学C

@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


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"


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜