ruby-on-rails - Ruby 未定义的哈希方法

标签 ruby-on-rails hash

我正在尝试使用以下代码将一个条目(已从键盘读取)添加到 Ruby 哈希:

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

“schemes”是我的哈希的名称,“schemeName”是我存储用户输入的数据的变量。但是,由于某种原因,我收到一条错误消息,指出“add”是一个未定义的方法...我认为这是哈希数据类型的内置方法?

我的类(class)的完整代码是:

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

有人可以指出为什么我收到未定义的方法错误吗?

最佳答案

Hash 没有 add 方法 ( see here )。它确实有 store ,它需要一个键和值对,因此您的代码可能会读取:

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

关于ruby-on-rails - Ruby 未定义的哈希方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12050685/

相关文章:

python - 散列 frozenset 与 tuple of sorted

ruby-on-rails - 将值从 View 传递到 Controller ,无需查询字符串

java - 散列密码和加盐密码并不总是相同的

python - 询问 "is hashable"有关 Python 值的信息

ruby-on-rails - Ruby 如何返回实例评估数组

hash - SHA1哈希是否均匀分布?

ruby - 如何根据 Ruby 中的值拆分散列?

ruby-on-rails - Stripe Connect API (Ruby) 用 "Managed Account": delete bank account, 添加多个银行账户

ruby-on-rails - Rails3 irb 控制台与 rails 控制台?

ruby-on-rails - 使用 facebook api 在 Facebook 上分享文章