Ruby 我的弦怎么了?
以下代码正在生成错误,我看不到问题。有人能帮忙吗Ruby 我的弦怎么了?,ruby,string-literals,Ruby,String Literals,以下代码正在生成错误,我看不到问题。有人能帮忙吗 customer_array = [‘Ken’,’William’,’Catherine’,’Mark’,’Steve’,’Sam’] customer_hash = { ‘Ken’ => ‘Fiction’, ‘William’ => ‘Mystery’, ‘Catherine’ => ‘Computer’, ‘Mark’ => ‘Fiction’, ‘Steve’ => ‘Sports’, ‘Sam’ =>
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'
# ^
问题似乎在于那些奇怪的反报价。请尝试以下方法:
customer_array = ["Ken","William","Catherine","Mark","Steve","Sam"]
customer_hash = {
"Ken" => "Fiction",
"William" => "Mystery",
"Catherine" => "Computer",
"Mark" => "Fiction",
"Steve" => "Sports",
"Sam" => "Fiction"
}
您有很多键=>值一个哈希包含一个键(在箭头之前)和一个值(在箭头之后) 您可以创建一个哈希数组。RubyonRails使用这个 你必须修正引号
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
然后你可以像这样绕着它转
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类上的许多方法
这里还有额外的方法
最后一个提示
试试这个
irb(main):039:0> customer_array_of_hashes.class
=> Array
irb(main):040:0> customer_array_of_hashes.first.class
=> Hash
如果你想知道ruby中有什么类,class方法会给出答案
好的,您知道customer\u数组是一个数组。可以在数组上使用的一种方法是
试试这个
irb(main):039:0> customer_array_of_hashes.class
=> Array
irb(main):040:0> customer_array_of_hashes.first.class
=> Hash
好的,这是一个哈希数组
好看 您的引号是非ASCII字符 将它们替换为ASCII
”
或“
或者将#encoding:UTF-8
添加到文件的开头,并将它们用ASCII引号括起来,如下所示:
# encoding: UTF-8
customer_hash = {
"‘Ken’" => "‘Fiction’",
}
你试过双引号吗?你也可以使用单引号,正如@slivu在他的回答中所说。单引号或双引号有效,但反向引号无效。