我想问你如何匹配散列中的nil值,例如: G:
string AccessKey = "xxx";
string SecretKey = "xxx";
string AppName = "ProductFunctionsApp";
string AppVersion = "1.0";
string ServiceURL = "https://mws.amazonservices.com/Products/2011-10-01";
string SellerId="xxxx";
string MarketPlaceId = "xxx";//US
//right now MWSAuthToken is only if a developer is using a sellers account
MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig();
config.ServiceURL = ServiceURL;
config.SignatureMethod = "HmacSHA256";
config.SignatureVersion = "2";
MarketplaceWebServiceProductsClient client = new MarketplaceWebServiceProductsClient(AppName, AccessKey, SecretKey, AppVersion, config);
ASINListType type = new ASINListType();
List<string> ASINList = new List<string>();
ASINList.Add("B001E6C08E");
type.ASIN = ASINList;
;
GetCompetitivePricingForASINRequest request = new GetCompetitivePricingForASINRequest();
request.SellerId = SellerId;
request.ASINList = type;
request.MarketplaceId = MarketPlaceId;
GetCompetitivePricingForASINResponse response = client.GetCompetitivePricingForASIN(request);
我怎样才能把动物&#39;在nil值或高于矩阵的长度的情况下,例如:
aAnimals = {1=>'dog', 2=>'cat'}
puts laAnimals[1] # dog
puts laAnimals[2] # cat
puts laAnimals[3] # nil
我想要这样的东西:laAnimals = {1=>'dog', 2=>'cat'}
laAnimals.default = 'no animal'
puts laAnimals[1] # dog
puts laAnimals[2] # cat
puts laAnimals[3] # no animal
......有可能吗?
答案 0 :(得分:3)
来自http://ruby-doc.org/core-2.2.0/Hash.html
哈希具有访问密钥时返回的默认值 哈希中不存在。如果未设置默认值,则使用nil。您可以 通过将其作为参数发送到:: new:
来设置默认值
因此,在您使用laAnimals = Hash.new("no animal")
的情况下,将使用字符串no animal
作为默认值。
答案 1 :(得分:2)
Exupery的回答是正确的,但如果您无法创建正在使用的哈希,则可以使用Hash#fetch
(docs)。
laAnimals = {1=>'dog', 2=>'cat'}
puts laAnimals.fetch(1, 'no animal') # dog
puts laAnimals.fetch(2, 'no animal') # cat
puts laAnimals.fetch(3, 'no animal') # 'no animal'
我个人更喜欢这种访问哈希的方法,因为如果密钥(在您的示例中,1
和2
)不存在,则会引发异常。