我有以下hash_of_student_and_grades。
{132=>{"Design"=>6, "English"=>5, "Humanities"=>5, "Languages"=>6, "Math"=>6, "Music"=>7,
"PE"=>6, "Science"=>6, "Theatre"=>6},
134=>{"Design"=>7, "English"=>6, "Humanities"=>6, "Languages"=>6, "Math"=>5, "Music"=>6,
"PE"=>6, "Science"=>7, "Art"=>6},
136=>{"Design"=>5, "English"=>4, "Humanities"=>5, "Languages"=>6, "Math"=>6, "Music"=>6,
"PE"=>7, "Science"=>5, "Theatre"=>6},...}
现在我想用这样的密钥创建哈希。
id132={"Design"=>6, "English"=>5, "Humanities"=>5, "Languages"=>6, "Math"=>6, "Music"=>7,
"PE"=>6, "Science"=>6, "Theatre"=>6}
id134={"Design"=>7, "English"=>6, "Humanities"=>6, "Languages"=>6, "Math"=>5, "Music"=>6,
"PE"=>6, "Science"=>7, "Art"=>6}
...
...
更新:
到目前为止我已经这样做了。但它不会将每个哈希值分配给密钥。
resulthash.each {|key, value| puts key=value}
# outputs
{"Design"=>6, "English"=>5, "Humanities"=>5, "Languages"=>6, "Math"=>6, "Music"=>7, "PE"=>6, "Science"=>6, "Theatre"=>6}
{"Design"=>7, "English"=>6, "Humanities"=>6, "Languages"=>6, "Math"=>5, "Music"=>6, "PE"=>6, "Science"=>7, "Theatre"=>6}
我该如何做到这一点?
答案 0 :(得分:1)
您不能将数字用作变量名,但如果它是id132,id133等,您可以使用元编程和实例变量来完成此操作:
hash = {"i1"=>{"a"=>"b"}, "i2"=>{"c"=>"d"}}
hash.each { |key, value| instance_variable_set("@#{ key }", value) }
puts @i1 # => {"a"=>"b"}
答案 1 :(得分:0)
在ruby id32
中是变量的名称
哈希的键可以是任何类型:数字,字符串......对象。
基本类型(数字,字符串,nil
,false
,true
)的评估方式如下:
n1 = 2
n2 = 2
h = {2 => 42}
h[n1] # 42
h[n2] # 42
换句话说,你得到/设置哈希的密钥2
而不是n1
或n2
。很难改变基本类型。
对象,另一方面,您可以修改:
class N
def initialize name
@name=name #contains name, like `id32`, `id34`
end
def to_s #this method let you show any text, here name(for example `id32`)
"#{@name}"
end
end
id32 = N.new 'id32'
h={id32 => 42}
#{id32=>42}
#adding more keys/values
id34 = N.new 'id34'
h[id34] = 'some value'
和......那只是基础。
它类似于字符串,但只能有一个符号!
puts :a.object_id
puts :a.object_id
puts :a.object_id
上面的代码打印3个相同的数字,因为:a
只有1。
puts 'a'.object_id
puts 'a'.object_id
字符串不一样。
您使用:
添加字符:
`:a`
或者如果它有奇怪的字符,请在:
前加上'
或"
:
:'a'
您的代码看起来完全一样,会更快(不需要上面的对象):
h ={:a => :b}
或从1.9.x(我记不起正确的数字)你也可以使用这种语法:
h = {a: :b}