红宝石中的新哈希声明与命令行相比返回语法错误

时间:2019-01-08 10:39:10

标签: ruby-on-rails ruby

我正在尝试在ruby中声明具有两个键和数组的新哈希作为相应键的值。 我不明白的问题是,当我在命令行中运行它时,与运行.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"],
...                              ^

3 个答案:

答案 0 :(得分:1)

:前没有空格。从

mtahash = {
  N : ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],
  L : ["8th", "6th", "Union_Square", "3rd", "1st"],
  }

mtahash = {
  N: ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],
  L: ["8th", "6th", "Union_Square", "3rd", "1st"],
  }

答案 1 :(得分:0)

您在键和冒号之间放置了空格,请尝试不使用空格:

N: ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],

答案 2 :(得分:0)

{ a: 23 }{ :a => 23 }的简写,仅用于符号键。而且您不能放置空格,因此a:有效,但a :无效。

根据红宝石约定,也不建议使用大写形式的符号(即使它可以工作),因此请使用:n而不是:N