Rspec 4 dictionary

I’m working on Dictionary in RSPEC 4, everything else works fine except for “printable” method, it would not only print [key] ‘definition’ as asked, but also would print the entire hash.

class Dictionary

def initialize(entries = {})
@entries = {}
end

def add(entries)
if entries.is_a?(Hash)
@entries.merge!(entries )
elsif entries.is_a?(String)
@entries.merge!({entries => nil})
end
end

def entries
@entries
end

def keywords
@entries.keys.sort!
end

def include?(word)
@entries.keys.include?(word)
end

def find(word)
finding = {}
@entries.each do |k,v|
if k.include?(word)
finding[k]=v
end
end
finding
end

def printable
@entries.each do |k,v|
puts “[#{k}] ‘#{v}’”
end
end

end

I ran in Replit :

new_entry = Dictionary.new

new_entry.add(“fish” => “aquatic animal”)
new_entry.add(“fiend” => “wicked person”)
new_entry.add(“great” => “remarkable”)
p new_entry.printable

And i GOT:
“[fish] ‘aquatic animal’”
“[fiend] ‘wicked person’”
“[great] ‘remarkable’”
{“fish”=>“aquatic animal”, “fiend”=>“wicked person”, “great”=>“remarkable”} #WHY DO I GET THE HASH?

I believe that you’re hash isn’t being printed but is being returned by the compiler. Ruby implicitly returns the last line of code in the method and in your case, the last line is the .each method that is being used on the hash. The .each method by default returns the original array or hash that you were iterating on it.

i just made a simple method to print out k and v in a hash using each, it does not return the hash itself:

def my_each(hash)
hash.each do |k,v|
puts “[#{k}] : ‘#{v}’”
end
end

my_each({“zebra” => “African land animal with stripes”, “fish” => “aquatic animal”, “apple” => “fruit”})

And I got:
[zebra] : ‘African land animal with stripes’
[fish] : ‘aquatic animal’
[apple] : ‘fruit’

That’s the difference between your my_each and Ruby’s own each: Your my_each doesn’t return hash at the end.