2011-04-19 64 views
2

的参数默认为空哈希attrs={}返回一个错误:空哈希作为默认参数变成数组?

can't convert Array into Hash 
(TypeError) 

我已经试过这对Ruby版本1.8.6,1.8.7和1.9.1。散列将被传递给attrs

class Category < Object 

    attr_accessor :attributes 
    attr_accessor :rel_attrs 
    attr_accessor :cls_str 

    def initialize (term='',title='', attrs={}, scheme = '', rel=[], cls_str='') 

    @attributes ={} 
    @attributes['scheme'] = scheme 
    @attributes['term'] = term 
    @attributes['title'] = title 
    @attributes['related'] = rel 
    @cls_str = cls_str 

    if not attrs.empty? 
     @attributes.update attrs 
    end 
    end 
end 

我在做什么错?

+1

你是如何调用initialize方法的,或者你在创建Category实例时传递了哪些参数? – 2011-04-19 08:26:46

+0

显示文件名和发生错误的位置。 – sawa 2011-04-19 13:36:44

回答

3

一些注意事项:

  • 您不必从Object继承。
  • if not可以更通俗地表示为unless
  • 使attrs散列最后一个参数的优点是,您可以在拨打Category.new时在散列元素周围留下{}。你可以而不是如果散列是中间的话,你可以这样做,因此向我们显示你的电话号码Category.new是有意义的。

我改变了相应的代码:

class Category 

    attr_accessor :attributes 
    attr_accessor :rel_attrs 
    attr_accessor :cls_str 

    def initialize (term='',title='', scheme = '', rel=[], cls_str='', attrs={}) 

    @attributes ={} 
    @attributes['scheme'] = scheme 
    @attributes['term'] = term 
    @attributes['title'] = title 
    @attributes['related'] = rel 
    @cls_str = cls_str 

    @attributes.update(attrs) unless attrs.empty? 
    end 
end 

这里是你怎么称呼它:

>> c = Category.new("term", "title", "scheme", [1,2,3], 'cls_string', :foo => 'bar', :baz => 'qux') 
#=> #<Category:0x00000100b7bff0 @attributes={"scheme"=>"scheme", "term"=>"term", "title"=>"title", "related"=>[1, 2, 3], :foo=>"bar", :baz=>"qux"}, cls_str"cls_string" 
>> c.attributes 
#=> {"scheme"=>"scheme", "term"=>"term", "title"=>"title", "related"=>[1, 2, 3], :foo=>"bar", :baz=>"qux"} 

这显然是其他所有可选参数都在为了要指定的问题能够指定attrs。如果你不想要这个,请将attrs移回参数列表的中间,并确保在呼叫中包含{}。或者甚至更好,使整个参数列表成为散列并将其与默认参数合并。类似于

class Category(opts = {}) 
    # stuff skipped 
    @options = { :bla => 'foo', :bar => 'baz'}.merge(opts) 
    # more stuff skipped 
end 
+0

此外,我建议简化方法签名,IMO看起来很糟糕。将所有可选参数移动到选项散列是非常普通的。 – tokland 2011-04-19 10:20:45

+0

这正是我在最后一段和代码片段中提出的建议:-) – 2011-04-19 10:40:47

+0

@Micahel。哦,对不起,我没有看到它。 – tokland 2011-04-19 12:36:37