以下代码生成错误,我看不到问题。有人可以帮忙吗?
customer_array = [‘Ken’,’William’,’Catherine’,’Mark’,’Steve’,’Sam’]
customer_hash = {
‘Ken’ => ‘Fiction’,
‘William’ => ‘Mystery’,
‘Catherine’ => ‘Computer’,
‘Mark’ => ‘Fiction’,
‘Steve’ => ‘Sports’,
‘Sam’ => ‘Fiction’
}
# => customer_array.rb:6: syntax error, unexpected tSTRING_BEG , expecting '}'
# 'William' => 'Mystery'
# ^
答案 0 :(得分:6)
问题似乎与那些奇怪的背引言有关。试试这个:
customer_array = ["Ken","William","Catherine","Mark","Steve","Sam"]
customer_hash = {
"Ken" => "Fiction",
"William" => "Mystery",
"Catherine" => "Computer",
"Mark" => "Fiction",
"Steve" => "Sports",
"Sam" => "Fiction"
}
答案 1 :(得分:1)
你的引号是非ASCII字符。
将其替换为ASCII '
或"
。
或将# encoding: UTF-8
添加到文件的开头并将其包装成ASCII引号,如下所示:
# encoding: UTF-8
customer_hash = {
"‘Ken’" => "‘Fiction’",
}
答案 2 :(得分:-1)
你有很多钥匙=>值哈希包含一个键(在箭头之前)和一个值(在箭头之后)
你可以制作一个哈希数组。 Ruby on rails使用它。
您必须修改引号
customer_hash = {
"Ken" => "Fiction",
"William" => "Mystery",
"Catherine" => "Computer",
"Mark" => "Fiction",
"Steve" => "Sports",
"Sam" => "Fiction"
}
但为什么不这样做
customer_array_of_hashes = [
{'Ken' => 'Fiction'},
{'William' => 'Mystery'},
{'Catherine' => 'Computer'},
{'Mark' => 'Fiction'},
{'Steve'=> 'Sports'},
{'Sam' => 'Fiction'}
]
然后你可以像这样循环播放
customer_array_of_hashes.each do|hash|
hash.each do |key, value|
puts "lastname: " + value + ", firstname: " + key
end
end
你可以在这里找到所有红宝石类的所有方法
并在此处使用额外的方法
最后一个提示
试试这个
irb(main):039:0> customer_array_of_hashes.class
=> Array
如果你想在ruby中使用哪个类,那么class方法就会给出答案。
好的,你知道customer_array_of_hashes是一个数组。您可以在数组上使用的一种方法是.first
试试这个
irb(main):040:0> customer_array_of_hashes.first.class
=> Hash
好吧,这是一系列哈希!
好看!