2012-11-16 24 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’", 
}