2012-11-16 20 views
-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' 
# ^
+0

你试过双引号? – KMC

回答

6

问题似乎与那些奇怪的后引号。试试这个:

customer_array = ["Ken","William","Catherine","Mark","Steve","Sam"] 
customer_hash = { 
    "Ken" => "Fiction", 
    "William" => "Mystery", 
    "Catherine" => "Computer", 
    "Mark" => "Fiction", 
    "Steve" => "Sports", 
    "Sam" => "Fiction" 
} 
+0

没错,就是这样,愚蠢的书教我走错了路;( – Ninja2k

+0

您也可以使用单引号,因为在@slivu他的回答说,单引号或双引号的作品,但反引号不会。 – tjameson

-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类

所有方法这里种

Ruby API

和Rails额外的方法

到底

Ruby on rails API

一个提示试试这个

irb(main):039:0> customer_array_of_hashes.class 
=> Array 

如果你wounder你有红宝石什么课类方法会给出答案。

好吧,你知道customer_array_of_hashes是一个数组。你可以在阵列使用的方法之一是。首先

试试这个

irb(main):040:0> customer_array_of_hashes.first.class 
=> Hash 

确定它是哈希数组!

好看!

1

您的报价均为非ASCII字符。

与ASCII '"替换它们。

或添加# encoding: UTF-8到您的文件的开头,它们包装成ASCII引号,像这样:

# encoding: UTF-8 

customer_hash = { 
    "‘Ken’" => "‘Fiction’", 
}