输入具有默认值的哈希

时间:2012-03-17 21:55:33

标签: ruby ruby-1.9

我想将哈希集的各个成员初始化为默认值,我尝试了以下内容:

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作为庄园初始化的参数,将哈希的各个成员的默认值设置为自己的哈希?

1 个答案:

答案 0 :(得分: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

这将允许在散列中传递其他属性,但我认为这是可取的,因为您故意使用可扩展输入开始。

相关问题