English 中文(简体)
在废墟中,为什么阵列在一只有空阵的违约值的散射中失败? [复制]
原标题:In ruby, why does array append fail on a hash with a default value of empty array? [duplicate]

守则例如下。 要求正确获得厚价回报,但 has本身并没有像我所期望的那样行事。

ruby-1.9.2-p290 :037 >   r = {}
 => {} 
ruby-1.9.2-p290 :038 > r.default = []
 => [] 
ruby-1.9.2-p290 :039 > r["c"] << 1
 => [1] 
ruby-1.9.2-p290 :040 > r["c"] 
 => [1] 
ruby-1.9.2-p290 :041 > r
 => {} 
ruby-1.9.2-p290 :042 > r.empty?
 => true 
最佳回答

http://www.un.org/Depts/DGACM/index_french.htm

Sets the default value, the value returned for a key that does not exist in the hash. It is not possible to set the default to a Proc that will be executed on each key lookup.

因此,你可以这样做:

irb(main):037:0> h = Hash.new { |hash, key| hash[key] = [] }
=> {}
irb(main):038:0> h[1] << "2"
=> ["2"]
irb(main):039:0> h
=> {1=>["2"]}

也可使用default_proc:

irb(main):047:0> h = {}
irb(main):047:0> h.default_proc =  proc {|hash, key| hash[key] = []}
=> #<Proc:0x23939a0@(irb):47> 
irb(main):049:0> h[1] << 3
=> [3]
irb(main):050:0> h
=> {1=>[3]}
问题回答

It seems ruby hash uses r.default as default value for any r[<unassigned-key>]. So a single value is changed even if you specify different un-assigned keys. Please see below:

irb(main):001:0> r = {}
=> {}
irb(main):002:0> r.default = []
=> []
irb(main):003:0> r["c"] << 1
=> [1]
irb(main):004:0> r["c"]
=> [1]
irb(main):005:0> r["b"] << 2
=> [1, 2]
irb(main):006:0> r["b"]
=> [1, 2]
irb(main):007:0> r["c"]
=> [1, 2]
irb(main):010:0> r.default
=> [1, 2]
irb(main):008:0> r
=> {}
irb(main):009:0> r.empty?
=> true




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签