tomtom
tomtom

Reputation: 1190

Ruby custom method to fill hash

I'm working on a method that will allow me to add in a "word" and its "definition", into a hash.

Here's what I have:

class Dictionary
def entries
 @entries ||= {}

end

def add word, definition = nil
    entries[word] = definition
    "#{entries}"
end

end

Note: I want the definition parameter to be optional, hence my initialization to nil. However, for some reason that is showing up in my output.

Example: Passing in "fish" and "aquatic animal":

My output: {{"fish"=>"aquatic animal"}=>nil}

Desired output: {"fish"=>"aquatic animal"}

It seems like the problem is that it's putting both values that I pass to the method into the first key in the hash, and is putting that "nil" value into that key's value. Where am I making an error?

Edit: Adding the relevant RSpec block that is doing the method call so that I can better understand exactly how RSpec is making this call:

describe Dictionary do
  before do
    @d = Dictionary.new
  end

  it 'is empty when created' do
    @d.entries.should == {}
  end

  it 'can add whole entries with keyword and definition' do
    @d.add('fish' => 'aquatic animal')
    @d.entries.should == {'fish' => 'aquatic animal'}
    @d.keywords.should == ['fish']
  end

Thanks!

Upvotes: 0

Views: 365

Answers (3)

SteveTurczyn
SteveTurczyn

Reputation: 36870

If you want to optionally accept a hash entry...

def add word, definition = nil
    if word.class == Hash
      entries.merge!(word)
    else
      entries[word] = definition
    end
    "#{entries}"
end

Upvotes: 1

Cereal
Cereal

Reputation: 3849

Your RSpec is wrong.

Change @d.add('fish' => 'aquatic animal') to @d.add('fish', 'aquatic animal')

Your #add method is accepting 2 parameters, with one being optional. With your current code, you're passing in a single hash 'fish' => 'aquatic animal'. Therefor setting word to the hash, and def to nil.

Upvotes: 1

SteveTurczyn
SteveTurczyn

Reputation: 36870

You don't want to do

 @d.add('fish' => 'aquatic animal')

You want to do...

 @d.add('fish', 'aquatic animal')

As it is, you're passing a hash as the first argument, second argument is empty.

Upvotes: 1

Related Questions