I am trying to declare the new hash in ruby having two keys and arrays as values to the respective keys. The problem I dont understand is when I run it in pry ie command line it doesn't give any syntax error compared to when I run a .rb
file. My codes are below.
[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
When I declare a new hash in .rb
file using same syntax, it returns the error,
mtahash = {
N : ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],
L : ["8th", "6th", "Union_Square", "3rd", "1st"],
}
puts mtahash[:N]
puts mtahash[:N][4]
Run and threw error as,
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"],
... ^
No spaces before the :
. Move from
mtahash = {
N : ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],
L : ["8th", "6th", "Union_Square", "3rd", "1st"],
}
to
mtahash = {
N: ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],
L: ["8th", "6th", "Union_Square", "3rd", "1st"],
}
You put space between your key and colon, try without it:
N: ["timesq", "34thn", "28thn", "23rdn", "Union_Square", "8th"],
etc.
{ a: 23 }
is shorthand for { :a => 23 }
just only for symbol keys. And you cannot put space so a:
is valid but not a :
.
Also using the capitalised form for a symbol is not preferred (even if it works) as per ruby convention so use :n
instead of :N
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.