A parameter defaulted to an empty hash attrs={} returns an error:
can't convert Array into Hash
(TypeError)
I’ve tried this on Ruby versions 1.8.6, 1.8.7 and 1.9.1. A hash will be passed to 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
What am I doing wrong?
Some notes:
Object.if notcan more idiomatically be expressed asunless.attrshash the last argument has the advantage that you can leave off the{}around the hash elements when callingCategory.new. You can not do this if the hash is the middle, so it would make sense to show us your call toCategory.new.I changed your code accordingly:
Here’s how you call it:
This obviously has the problem that all other optional arguments have to be specified in order to be able to specify
attrs. If you don’t want this, moveattrsback to the middle of the argument list and make sure to include the{}in the call. Or even better, make the whole argument list a hash and merge it with the defaults args. Something like