Devoted Enthusiast Devoted Enthusiast - 1 month ago 16
Ruby Question

Get array element by key

This is my

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


But when I try accessing:
/single/0
for example I get the following error:


TypeError at /single/1

no implicit conversion of String into Integer

Answer

Try

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

The param comes from the URL so it's a string.

Comments