Hash.new doesn't work in MyClass.new (or something similiar.)

P

possibilitybox

class IndexerHash
def new
@hash = Hash.new do |hash, input_key|
hash.each do |key, value|
return value if key.include? input_key
end
end
end
def [](key)
@hash[key]
end
def []=(key, value)
@hash[key]=value
end
def save
require "yaml"
output = YAML::dump(@hsh)
f = File.open('./index.yml', 'w')
f.write(output)
f.close
end
end

I get various errors related to what appears to be a malfunction of
Hash.new (but's probably me doing something wrong.). All of them raise
a NoMethodError for NilClass. (but hash isn't a Nil, is it?)

A hash created in an identical manner outside of IndexerHash.new works
as expected.

I'm using mac os x 10.4.6 on an macbook pro, irb 0.9.5 from
darwinports.

help!

(psst. if i didn't provide enough information, i'd be glad to provide
anything more that would help solving this problem.)
 
O

OliverMarchand

class IndexerHash
def new

(a) you should implement initialize and call new
@hash = Hash.new do |hash, input_key|
hash.each do |key, value|
return value if key.include? input_key
end
end

What are you trying to do here? Did you forget to pass an argument to
what should have been initialize.
output = YAML::dump(@hsh)

Typo!

cheers, Oliver
 
P

possibilitybox

Thanks! that solved it all. I just didn't know about implenting
initialize instead of new.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top