按键获取数组元素

时间:2016-11-02 11:33:59

标签: arrays ruby sinatra

这是我的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时,我收到以下错误:

  

/ single / 1

的TypeError      

没有将String隐式转换为整数

1 个答案:

答案 0 :(得分:2)

尝试

comic = COMICS[params['key'].to_i]

param来自路径,所以它是一个字符串。