%i in Ruby
Jul 4, 2021
A little ruby array with symbols trick
In a Ruby on Rails application, when I would set up my routes I would always write:
resources :trip_gears, only: :create#if more than one CRUD method:resources :trip_gears, only: [:create, :index]
I just found out that you can do this differently, syntactically, by using %i if creating an array of symbols. It looks like this:
resources :trips, only: %i[index create]
This allows you to get rid of the symbols in the array as well as the comma. Just a different way to write it out but it does the same thing.
If you need to interpolate in the array. you would use a %I (uppercase). There are other ways to write percent string literals with ruby. Here is a list of some other ones: