按键获取数组元素
Get array element by key
这是我的 app.rb
:
require 'sinatra'
COMICS = [
{
'name' => 'Test #1',
'code' => 'Link №1'
},
{
'name' => 'Test #2',
'code' => 'Test №2'
},
{
'name' => 'Test #3',
'code' => 'Test №3'
},
{
'name' => 'Test #4',
'code' => 'Test №4'
}
]
get '/' do
erb :index, :locals => { :comics => COMICS }
end
get '/single/:key' do
comic = COMICS[params['key']]
erb :single, :locals => { :comic => comic }
end
但是当我尝试访问时:例如 /single/0
我收到以下错误:
TypeError at /single/1
no implicit conversion of String into Integer
尝试
comic = COMICS[params['key'].to_i]
参数来自路径,所以它是一个字符串。
这是我的 app.rb
:
require 'sinatra'
COMICS = [
{
'name' => 'Test #1',
'code' => 'Link №1'
},
{
'name' => 'Test #2',
'code' => 'Test №2'
},
{
'name' => 'Test #3',
'code' => 'Test №3'
},
{
'name' => 'Test #4',
'code' => 'Test №4'
}
]
get '/' do
erb :index, :locals => { :comics => COMICS }
end
get '/single/:key' do
comic = COMICS[params['key']]
erb :single, :locals => { :comic => comic }
end
但是当我尝试访问时:例如 /single/0
我收到以下错误:
TypeError at /single/1
no implicit conversion of String into Integer
尝试
comic = COMICS[params['key'].to_i]
参数来自路径,所以它是一个字符串。