Someone2088
Someone2088

Reputation: 141

Ruby undefined method for hash

I'm trying to add an entry (that has been read from the keyboard) to a Ruby hash using the following code:

if schemes.has_key?(schemeName)
   puts "This scheme has already been added "
 else
   schemes.add(schemeName)
 end

'schemes' is the name of my hash and 'schemeName' is the variable in which I've stored the data entered by the user. However, for some reason, I'm getting an error saying that 'add' is an undefined method... I thought that that was a built in method for the hash data type?

The full code for my class is:

class CourseModules
# To change this template use File | Settings | File Templates.
@@moduleScheme = nil
@@moduleYear = nil
#@moduleTitle = ""
@noOfModulesInScheme = 0

def self.moduleYear
 @@moduleYear
end

def initialize(v)
 @val = v
end
# Set and get the @val object value
def set (v)
 @val = v
end
def get
 return @val
end

def addModule
 moduleName = Module.new(30)
 moduleRefNo = Random(100)
 #moduleTitle = @moduleTitle
 moduleYear(4)

 print "What is the name of the module you would like to add?"
 moduleName = gets
 moduleRefNo
 printf "Which year does the module belong to?"
 @@moduleYear = gets
 puts "#{moduleName}, belonging to #{@@moduleYear} has been added to the system, with reference number #{moduleRefNo}."
 navigateTo Application

end

def self.addModuleToScheme
=begin
Create an empty hash for the schemes
=end
 schemes = Hash.new()
=begin
Allow user to enter scheme names into a set of variables, and use each scheme name as a hash/ array of modules.
Then allow the user to enter the the modules for each scheme into each of the hashes

Create specific hash elements by using the following line:
schemes = {:scheme1 => scheme1variable, :scheme2 => scheme2variable}
=end

 puts "What is the name of the scheme that you would like to add a module to? "
 schemeName = gets
=begin
Need to use an if statement here to check whether or not the scheme already exists, if it doesn't, create it, if it does,
tell the user that it does.
=end
 if schemes.has_key?(schemeName)
   puts "This scheme has already been added "
 else
   schemes.add(schemeName)
 end

 noOfModulesInScheme + 1
 moduleName.moduleScheme = schemeName
end
def removeModuleFromScheme
 moduleName.moduleScheme = nil
end

def queryModule

end

end

Could someone point out why I'm getting an undefined method error?

Upvotes: 2

Views: 6642

Answers (1)

ScottJShea
ScottJShea

Reputation: 7111

Hash does not have an add method (see here). It does have store which requires a key & value pair so your code might read:

if schemes.has_key?(schemeName)
   puts "This scheme has already been added "
else
   schemes.store(schemeName, scheme)
end

Upvotes: 3

Related Questions