Forum: Ruby dynamic assignment of iterator name

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
3accfb92a7a47de5a84e71da69d57210?d=identicon&s=25 Leah Cunningham (heinous)
on 2006-03-06 00:07
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.
25e11a00a89683f7e01e425a1a6e305c?d=identicon&s=25 Wilson Bilkovich (Guest)
on 2006-03-06 00:15
(Received via mailing list)
On 3/5/06, Leah Cunningham <leah@heinous.org> wrote:
>         end
>               user.mail = params[:user][attr]
>             when "o"
>               user.o = 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}=", value)
end
This topic is locked and can not be replied to.