2012-03-17 73 views
2

我想設置爲默認值的散列的各個成員初始化類的,我已經試過如下:輸入默認值的哈希

class SomeClass 
    attr_accessor :hello, :holla 
    def initialize (hash = { hello: 'world', holla: 'mundo'}) 
    @hello = hash[:hello] 
    @else = hash[:holla] 
end 
end 

根據需要,如果不輸入任何其中工程參數

p = SomClass.new 
puts "should be 'world'" 
puts p.hello 
puts "should be 'mundo'" 
puts p.holla 

$ruby hello_world.rb 
should be 'world' 
universe 
should be 'mundo' 
mundo 

但如果散列的增強件中的一個被設置其它爲空,例如:

p = SomeClass.new({ hello: 'universe'}) 
puts "should be 'universe'" 
puts p.hello 
puts "should be 'mundo'" 
puts p.holla 

$ruby hello_world.rb 
should be 'universe' 
universe 
should be 'mundo' 

如何輸入hash作爲莊園初始化的參數,爲散列的各個成員設置默認值只是它自己的散列?

回答

5

沒有自定義代碼,沒有辦法做到這一點。的,最簡單的版本是:

def initialize(hash = {}) 
    hash = {hello: "world", holla: "mondo"}.merge(hash) 
    # now your default values are set, but will be overridden by the passed argument 
end 

這將允許其他屬性在哈希傳遞,但我認爲是可取的,因爲你故意使用一個可擴展的輸入開始。