dynamic assignment of iterator name

  • Thread starter Leah Cunningham
  • Start date
L

Leah Cunningham

I apologize if this is a foolish questions, but I am new to the language
and having trouble finding an example of what I am looking to do (if
it's possible.)

I would like to know if there is a way to pass in the name of the
iterator to use from a variable or similar. I am looking to do
something like:

params[:user].each_key do |attr|
user.attr = params[:user][attr]
end

For now I can just use a giant case statement like this:

params[:user].each_key do |attr|
case attr
when "givenName"
user.givenName = params[:user][attr]
when "sn"
user.sn = params[:user][attr]
when "mail"
user.mail = params[:user][attr]
when "o"
user.o = params[:user][attr]
end
end

But it would be nice to know if there is a cleaner way to handle this.
 
W

Wilson Bilkovich

I apologize if this is a foolish questions, but I am new to the language
and having trouble finding an example of what I am looking to do (if
it's possible.)

I would like to know if there is a way to pass in the name of the
iterator to use from a variable or similar. I am looking to do
something like:

params[:user].each_key do |attr|
user.attr =3D params[:user][attr]
end

For now I can just use a giant case statement like this:

params[:user].each_key do |attr|
case attr
when "givenName"
user.givenName =3D params[:user][attr]
when "sn"
user.sn =3D params[:user][attr]
when "mail"
user.mail =3D params[:user][attr]
when "o"
user.o =3D params[:user][attr]
end
end

You can use "send" for this, and using the multi-variable block on
'each' will save you a further step.

params[:user].each do |key, value|
user.send("#{key}=3D", value)
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top