Why do Ruby think this is a symbol

Hello,

I have this script:

def solution(keys, default_value)
answer = Hash.new(default_value)
keys.each { |k| answer.add k }
end

and this test file :

Test.assert_equals( {:draft => 0, :completed => 0}, solution([:draft,
:completed], 0))

But now I see this error message :

NoMethodError: undefined method `add’ for {}:Hash

Roelof

Your calling .add on answer (which is a hash) within your each block.

.add is a method for Set not Hash.
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/set/rdoc/Set.html

What are you trying to accomplish with this method??

Todd Pickell
Software Developer & Consultant

On May 30, 2014 at 3:46:42 PM, Roelof W. ([email protected]) wrote:

Hello,

I have this script:

def solution(keys, default_value)
answer = Hash.new(default_value)
keys.each { |k| answer.add k }
end

and this test file :

Test.assert_equals( {:draft => 0, :completed => 0}, solution([:draft,
:completed], 0))

But now I see this error message :

NoMethodError: undefined method `add’ for {}:Hash

Roelof

There is no method Hash#add() , does not exist. What you want to
acomplish I think is this:

def solution(keys, default_value)
answer = Hash.new(default_value)
keys.each { |k| answer[add] = default_value }
end

Try to refer to the documentation. If you have Ruby installed in
Windows by Ruby Installer you should have a folder with a *.chm file
with documentation. Other way there is the online Ruby API
documentation, google it.

ups was wrong

Damián M. González wrote in post #1147846:

There is no method Hash#add() , does not exist. What you want to
acomplish I think is this:

def solution(keys, default_value)
answer = Hash.new(default_value)
keys.each { |k| answer[add] = default_value }
end

I am not sure this is what OP wants. I’d rather guess (notice the usage
of “k”):

def solution(keys, default_value)
answer = Hash.new(default_value)
keys.each { |k| answer[k] = default_value }
end

But that does not make sense because the whole point of the default
value of a Hash is that the key does not need to be there to return the
default value when queried.

There also seems a more fundamental issue: “answer” goes nowhere, it is
not returned. But if one takes these two points together, then there is
really nothing left which justifies a method:

def solution(keys, default_value)
Hash.new(default_value)
end

That method is basically superfluous and can be replaced by the single
line it contains.

So, Roelof, what do you want to achieve?

I am not sure this is what OP wants. I’d rather guess (notice the usage
of “k”):

def solution(keys, default_value)
answer = Hash.new(default_value)
keys.each { |k| answer[k] = default_value }
end

Yes Robert, was my fault, did it quickly, thanks for correct.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs