Search code examples
rubysinatrainstance-variables

How to create instance variables with iterator


I have a lab through school where I need to create a form that takes in basketball team attributes, team name, coach, point guard etc., and want to know if there is any way to dynamically create instance variables and symbols using an iterator of sorts instead of hard coding them?

Here is the hard-coded version of what I mean:

post "/team" do
  @name = params["name"]
  @coach = params["coach"]
  @pg = params["pg"]
  @sg = params["sg"]
  @pf = params["pf"]
  @sf = params["sf"]
  @c = params["c"]
  erb :team
end

I want to use something similar to this:

post '/team' do
  params.each do |parameter|
    @[parameter] = params["#{parameter}"]
  end
  erb :team
end

When I run the above code I receive a unexpected end-of-input syntax error.


Solution

  • Try to use instance_variable_set, something like this:

    post '/team' do
      params.each do |key, value|
        self.instance_variable_set("@#{key}", value)
      end
      erb :team
    end