我的情况是XDocument doc = new XDocument(new XElement("checkout",
new XElement("currency","BRL"),
new XElement("items",
new XElement("item",
new XElement("id", "0001"),
new XElement("description", "caneca"),
new XElement("amount","10.00"),
new XElement("quantity","1"),
new XElement("weight","50"))),
new XElement("reference", "REF5678"),
new XElement("sender",
new XElement("name","Nathiel"),
new XElement("email", "joanito@sandbox.pagseguro.com.br"),
new XElement("phone",
new XElement("areacode","51"),
new XElement("number", "95453305"))),
new XElement("shipping",
new XElement("type","1"),
new XElement("adress",
new XElement("street","Rua da Insanidade"),
new XElement("number","102"),
new XElement("complement","CASA"),
new XElement("district","centro"),
new XElement("postalcode","54315310"),
new XElement("city","Recife"),
new XElement("state","PE"),
new XElement("country","Brasil")))));
doc.Save("document.xml");
似乎修改了CONST的值。这会发生吗?怎么样?
我正在做一些API摄取和映射,就像你做的那样 ......
merge!
稍后,我将其包含在API客户端的类中,然后调用module Placement
FEATURE_DEFAULTS = {
"thingone" => "false",
"thingtwo" => "false"
}
def extract_features!(feat)
feat['norm_features'] ||= FEATURE_DEFAULTS
feat['norm_features'].merge!(
Array(feat['attributes']['feature']).reduce({}) do |h,f|
h[f] = "true"
h
end
)
end
def get_placement(_opts)
data_source["things"]["thing"].map do |thing|
product = {}
thing.each do |key, value|
new_key = RENAME_FIELDS[key] || key
new_value = REPLACE_FIELDS[key] || value
product[new_key] = new_value
end
binding.pry # 1
extract_features!(product)
binding.pry # 2
product
end
end
end
方法。
对于第一次运行,在pry绑定1& 2,get_placement
的值如上所示。对于2,FEATURE_DEFAULTS
的值相同,FEATURE_DEFAULTS
的值相同(加上product['norm_features']
每个extract_features!
/产品的输出(caller
的{{1}})是
get_placement
当我第二次(启动服务/应用程序后)运行时,thing
的值和pry binding 1& 2,是
FEATURE_DEFAULTS = {
"thingone" => true,
"thingtwo" => true
}
这里发生了什么?
这似乎证实,在运行
FEATURE_DEFAULTS
方法后,FEATURE_DEFAULTS = { "thingone" => true, "thingtwo" => true }
CONST已更改。如果我不在extract_features!
中使用FEATURE_DEFAULTS
,而是使用merge!
,则CONST值不会更改。
如果需要,我可以发布更多代码,或者大部分内容都发布给Gist Ruby MRI 2.2.2
我在rails应用程序中执行此操作,但我不认为这很重要。
答案 0 :(得分:3)
我的情况是
merge!
似乎修改了CONST的值。这会发生吗?怎么样?
不,通常,方法不能更改变量绑定,无论这些变量是局部变量,实例变量,类变量,全局变量还是常量。变量不是Ruby中的对象,你不能在它们上调用方法,你不能将它们作为参数传递给方法,因此你不能告诉它们改变自己。
例外情况是Binding#local_variable_set
,Object#instance_variable_set
,Module#class_variable_set
或Module#const_set
等元编程方法。
本身。遗憾的是,Hash#merge!
的文档有点不清楚,因为它明确提及Hash#merge!
变异其接收者。
这似乎证实,在运行
extract_features!
方法后,FEATURE_DEFAULTS
CONST已更改。如果我不在merge!
中使用extract_features!
,而是使用merge
,则CONST值不会更改。
不,它只确认对象FEATURE_DEFAULTS
指向的状态发生了变化,它没有说明是否FEATURE_DEFAULTS
的绑定,即它指向哪个对象,已更改。您可以通过查看object_id
来确认常量仍然指向同一个对象。
当然,无论如何都可以重新分配常数,尽管会引发警告。