Ruby on rails 与命令行相比,ruby中的新哈希声明返回语法错误
我试图在ruby中声明新的散列,它有两个键和数组作为相应键的值。 我不明白的问题是,当我在pry(即命令行)中运行它时,与运行Ruby on rails 与命令行相比,ruby中的新哈希声明返回语法错误,ruby-on-rails,ruby,Ruby On Rails,Ruby,我试图在ruby中声明新的散列,它有两个键和数组作为相应键的值。 我不明白的问题是,当我在pry(即命令行)中运行它时,与运行.rb文件时相比,它没有给出任何语法错误。我的代码如下 [1] pry(main)> newhash = { [1] pry(main)* N: ["unsq", "34n","28"], [1] pry(main)* L: ["aston", "timesq", "place"] [1] pry(main)* } => {:N=>["unsq
.rb
文件时相比,它没有给出任何语法错误。我的代码如下
[1] pry(main)> newhash = {
[1] pry(main)* N: ["unsq", "34n","28"],
[1] pry(main)* L: ["aston", "timesq", "place"]
[1] pry(main)* }
=> {:N=>["unsq", "34n", "28"], :L=>["aston", "timesq", "place"]}
[2] pry(main)> newhash[:N]
=> ["unsq", "34n", "28"]
[3] pry(main)> newhash[:N][1] #returns the correct values
=> "34n" #returns the correct values
当我在.rb
文件中使用相同语法声明新哈希时,它返回错误
mtahash = {
N : ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],
L : ["8th", "6th", "Union_Square", "3rd", "1st"],
}
puts mtahash[:N]
puts mtahash[:N][4]
运行并抛出错误作为
MTA.rb:2: syntax error, unexpected ':', expecting =>
N : ["Times_Square", "34thn", "2...
^
MTA.rb:2: syntax error, unexpected ',', expecting end-of-input
...23rdn", "Union_Square", "8th"],
... ^
Farwas-MBP:day2 farwaabid$ ruby MTA.rb
MTA.rb:2: syntax error, unexpected ':', expecting =>
N : ["timesq", "34thn", "28thn",...
^
MTA.rb:2: syntax error, unexpected ',', expecting end-of-input
...23rdn", "Union_Square", "8th"],
... ^
:
前面没有空格。离开
mtahash = {
N : ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],
L : ["8th", "6th", "Union_Square", "3rd", "1st"],
}
到
如果在键和冒号之间留有空格,请尝试不使用:
N: ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],
等等。
{a:23}
是{:a=>23}
的简写,仅用于符号键。您不能放置空格,因此a:
有效,但a:
无效
此外,根据ruby约定,不建议使用大写形式作为符号(即使它有效),因此请使用:n
而不是:n
提示:您说您使用的是“相同的语法”,但您没有。
N: ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],