-1

以下代码生成错误,我看不到问题。任何人都可以帮忙吗?

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'
#      ^
4

3 回答 3

6

问题似乎出在那些奇怪的反引号上。试试这个:

customer_array = ["Ken","William","Catherine","Mark","Steve","Sam"]
customer_hash = {
    "Ken" => "Fiction",
    "William" => "Mystery",
    "Catherine" => "Computer",
    "Mark" => "Fiction",
    "Steve" => "Sports",
    "Sam" => "Fiction"
}
于 2012-11-16T08:04:28.247 回答
1

您的引号是非 ASCII 字符。

将它们替换为 ASCII'".

或添加# encoding: UTF-8到文件的开头并将它们包装成 ASCII 引号,如下所示:

# encoding: UTF-8

customer_hash = {
  "‘Ken’" => "‘Fiction’",
}
于 2012-11-16T08:36:46.820 回答
-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

你可以在这里找到所有 ruby​​ 类的所有方法

红宝石 API

并在这里添加额外的方法

Ruby on rails API

最后一个提示

试试这个

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

好的,这是一个哈希数组!

好看!

于 2012-11-16T08:21:56.327 回答